Create Bar Graph using Python Turtle

Create Bar Graph using Python Turtle

In this article, we will learn about how to Create Bar Graph using Python Turtle. The Code will be given below. Similarly, this article will teach you how you can write code in a turtle that will allow you to create your own designs and creations. We will first see the code and then, we will understand. Now let’s write the code for the graph.


Code:


import turtle


def bar_graph(var1, value):
    var1.begin_fill()
    var1.left(90)
    var1.forward(value)
    var1.write(" " + str(value))

    var1.right(90)
    var1.forward(40)
    var1.right(90)
    var1.forward(value)
    var1.left(90)
    var1.end_fill()
    var1.forward(10)


a = turtle.Screen()
a.bgcolor("black")
var1 = turtle.Turtle()
var1.color("green", "white")
var1.pensize(3)
measureheight = [48, 177, 200, 240, 160, 220]
for i in measureheight:
    bar_graph(var1, i)

a.mainloop()

Output:




Explanation:


First Part:

  • First, import the “turtle” module and set the “gajurel” variable to turtle.Screen(). Then, set the background color of the screen to “black”. And set the value of the “Ankur” variable as the turtle. Then, set the color of the turtle to “green” and “white” and the pen size to 3.

Second Part (The Function):

  • Second, create a function name barGraph() and set the parameters “ankur” and “var”. Now, start to fill the screen. Move left at an angle of 90 degrees and forward at the value of “var”. And, write the number “var” on the screen by converting it into a string.
  • Likewise, move right at an angle of 90 and forward at the value of 40. Then, move right again at n angle of 90 and forward at the value of “var”.
  • Similarly, move the turtle again towards the left at an angle of 90 and end the fill. And at the last of the function, move the turtle forward at the value of 10.

Last Part:

  • In this part, we will set the values to be graphed on the bar graph in the form of a list and store it in the variable “heightMeasurement”.
  • Accordingly, create a for loop which will loop through the values of the variable “heightMeasurement”. And inside this loop, call the barGraph() function with the arguments “ankur” and “I”.
  • Lastly, end the code by finishing the main loop.

Thanks for reading. Comment your queries if you have any. If you liked this Bar Graph with Python Turtle, there are other posts in turtle too.

Tell us if you found something wrong in this article.

Keep Learning, Keep Coding


Also Read:



    Share:

    Author: Ayush Purawr