Skip to content

Instantly share code, notes, and snippets.

@CORDEA
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CORDEA/e0947e4658ffddfd9785 to your computer and use it in GitHub Desktop.
Save CORDEA/e0947e4658ffddfd9785 to your computer and use it in GitHub Desktop.
Draw bar chart using the turtle module.
#!/usr/bin/env python
#coding: utf-8
class DrawGraph():
def set_data(self):
# x軸目盛, y軸目盛, 棒グラフの数値をリストにして格納する。
# 今回はサンプルなので適当にfor文で。
for i in range(10):
xList.append(str(i + 1))
for i in range(5):
yList.append(str((i + 1) * 20))
for i in range(10):
barList.append(str((i + 1) * 50))
def setup(self):
tG.hideturtle()
tGl.hideturtle()
tL.hideturtle()
tX.up()
tY.up()
tG.up()
tGl.up()
tL.up()
tX.setpos(-500, -250)
tY.setpos(-500, -250)
tG.setpos(-500, -250)
tGl.setpos(-500, -250)
def x_axis(self):
tX.down()
for i in range(10):
tX.forward(100)
tX.right(90)
tX.forward(20)
tX.up()
tX.forward(XYmargin)
tX.write(xList[i], False, align="center", font=(fontname, 10, "normal"))
tX.right(180)
tX.forward(20 + XYmargin)
tX.down()
tX.right(90)
tX.forward(50)
def y_axis(self):
# 始めに0だけ書いておく
tY.up()
tY.setpos(-500 + zero_pos, -250 + zero_pos)
tY.write("0", True, align="center", font=(fontname, 10, "normal"))
tY.setpos(-500, -250)
tY.down()
tY.left(90)
for i in range(5):
tY.forward(100)
tY.left(90)
tY.forward(20)
tY.up()
tY.forward(XYmargin)
tY.write(yList[i], False, align="center", font=(fontname, 10, "normal"))
tY.left(180)
tY.forward(20 + XYmargin)
tY.down()
tY.left(90)
tY.forward(50)
# 目盛線を点線で書くための関数
def gridline(self):
for i in range(5):
tGl.setpos(-500, -250 + 100 * (i + 1))
# 1回辺りの移動量(この場合は5+5で10)でグラフサイズを割る
for j in range(1050 / 10):
tGl.down()
tGl.forward(5)
tGl.up()
tGl.forward(5)
def draw_bar(self):
tG.forward(100 - bar_width / 2)
for i in range(10):
tG.left(90)
tG.down()
tG.forward(int(barList[i]))
tG.right(90)
tG.forward(bar_width)
tG.right(90)
tG.forward(int(barList[i]))
tG.left(90)
tG.up()
tG.forward(100 - bar_width)
def label(self):
tL.sety(-250 + 500 + 70)
tL.write(title, False, align="center", font=(fontname, 25, "normal"))
tL.sety(-250 - 20 - XYmargin - 30)
tL.write(xlabel, False, align="center", font=(fontname, 12, "normal"))
tL.setpos(-500, 250 + 60)
tL.write(ylabel, False, align="center", font=(fontname, 12, "normal"))
if __name__=='__main__':
import turtle
turtle.setup(1200, 800)
# グラフサイズは 1050x550
tX = turtle.Pen()
tY = turtle.Pen()
tG = turtle.Pen()
tGl = turtle.Pen()
tL = turtle.Pen()
xList = []
yList = []
barList = []
zero_pos = -10
# 棒の幅
bar_width = 40
XYmargin = 30
fontname = "Times New Roman"
# グラフタイトル, ラベル名
title = "Figure01. Sample graph"
xlabel = "xLabel"
ylabel = "yLabel"
graph = DrawGraph()
graph.set_data()
graph.setup()
graph.label()
graph.x_axis()
graph.y_axis()
graph.draw_bar()
graph.gridline()
turtle.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment