Python program to draw a bar chart using turtle
Prerequisite: Turtle Programming Basics
Turtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like a turtle.forward(…) and turtle.right(…) which can move the turtle around. Turtle is a beginner-friendly way to learn Python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways.
To draw, Python turtle provides many functions and methods i.e. forward, backward, etc. Some commonly used methods are:
- forward(x): moves the pen in the forward direction by x unit.
- backward(x): moves the pen in the backward direction by x unit.
- right(x): rotate the pen in the clockwise direction by an angle x.
- left(x): rotate the pen in the anticlockwise direction by an angle x.
- penup(): stop drawing of the turtle pen.
- pendown(): start drawing of the turtle pen.
Turtle can be used to draw any static shape (Shape that can be drawn using lines). We all know that
Approach:
- Import the turtle library.
- Create a function, say drawBar() that takes a turtle object, a height value, and a color name and perform the following steps:
- The function draws vertical rectangles of a given height and fixed width (say 40).
- The function fills the rectangle with the given color name.
- Initialize a list having some numerical values (data for the bar graph).
- Initialize a turtle instance.
- Set up the window and call the drawBar() for each value of the list with the created turtle instance and any color of your choice.
- After completing the above steps, close the turtle instance.
Below is the implementation of the above approach:
# Python program to draw a turtle
import turtle
# Function that draws the turtle
def drawBar(t, height, color):
# Get turtle t to draw one bar
# of height
# Start filling this shape
t.fillcolor(color)
t.begin_fill()
t.left(90)
t.forward(height)
t.write(str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
# stop filling the shape
t.end_fill()
# Driver Code
xs = [48, 117, 200, 96, 134, 260, 99]
clrs = ["green", "red", "yellow", "black",
"pink", "brown", "blue"]
maxheight = max(xs)
numbers = len(xs)
border = 10
# Set up the window and its
# attributes
wn = turtle.Screen()
wn.setworldcoordinates(0 - border, 0 - border,
40 * numbers + border,
maxheight + border)
# Create tess and set some attributes
tess = turtle.Turtle()
tess.pensize(3)
for i in range(len(xs)):
drawBar (tess, xs[i],
clrs[i])
wn.exitonclick()
Output: