Draw Graph Grid Using Turtle in Python
Prerequisite: Turtle Programming Basics
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Approach:
Following steps are used :
- Import turtle
- Set screen
- Make turtle
- Draw the y-axis lines
- Draw the x-axis lines
- Draw the x-axis and y-axis with labeling.
Below is the implementation :
Python3
# import package and making objectsimport turtlesc=turtle.Screen()trtl=turtle.Turtle()# method to draw y-axis linesdef drawy(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(val,300) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(val+10,0) trtl.down() # method to draw y-axis linesdef drawx(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(300,val) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(0,val+10) trtl.down() # method to label the graph griddef lab(): # set position trtl.penup() trtl.setpos(155,155) trtl.pendown() # write 0 trtl.write(0,font=("Verdana", 12, "bold")) # set position again trtl.penup() trtl.setpos(290,155) trtl.pendown() # write x trtl.write("x",font=("Verdana", 12, "bold")) # set position again trtl.penup() trtl.setpos(155,290) trtl.pendown() # write y trtl.write("y",font=("Verdana", 12, "bold")) # Main Section# set screensc.setup(800,800) # set turtle featurestrtl.speed(100)trtl.left(90) trtl.color('lightgreen')# y linesfor i in range(30): drawy(10*(i+1))# set position for x linestrtl.right(90)trtl.up()trtl.setpos(0,0)trtl.down()# x linesfor i in range(30): drawx(10*(i+1))# axistrtl.color('green')# set position for x axistrtl.up()trtl.setpos(0,150)trtl.down()# x-axistrtl.forward(300)# set position for y axistrtl.left(90)trtl.up()trtl.setpos(150,0)trtl.down()# y-axistrtl.forward(300)# labelinglab()# hide the turtletrtl.hideturtle() |
Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course



