在高年级小学数学课中,有关于柱状图的内容,现在用Python turtle来实现
柱状图效果
from turtle import *
from random import randint
data = []
length = 10
# 可以定义初始化数据集合的函数并返回列表
def init_data(num):
'''
用来初始化数据集的函数
但是返回列表对于学生难以理解
不过可以用,init_data同学,给我个列表把,
init_data同学回答说我给你列表
'''
data = []
count = 0
while count < num:
data.append(randint(1, 100)) # 这里是随机数据
# 实际运用中要用真实数据
# a = int(input('pls input a number:'))
# data.append(a)
count += 1
return data
apple = init_data(length)
peach = init_data(length)
print('苹果的数量分别是: ' + str(apple))
print('桃子的数量分别是: ' + str(peach))
def rect(x, y, width, height):
pu()
goto(x, y)
pd()
begin_fill()
goto(x + width, y)
goto(x + width, y + height)
goto(x, y + height)
# goto(x, y)
end_fill()
pu()
# rect(0, 0, 20, 200)
startx = -280
starty = 0
count = 0
gap = 10
bar_width = 20
def change_color(color):
'''
同时改变画笔和填充色
'''
fillcolor(color)
pencolor(color)
while count < len(apple):
# 这里的几何关系是比较难讲的
x = startx + count * (gap + bar_width * 2)
y = 0
# fillcolor('red')
# pencolor('red') # 开始先这样写,后面抽象为函数
change_color('red')
rect(x, y, bar_width, apple[count])
write(str(apple[count]))
# 以上3行代码也是可以抽象为函数的
# 为什么是加一个长度条的宽度呢
x = x + bar_width
# fillcolor('blue')
# pencolor('blue') # 开始先这样写,后面抽象为函数
change_color('green')
rect(x, y, bar_width, peach[count])
write(str(peach[count]))
# 以上3行代码也是可以抽象为函数的
# 如果要3组及其以上的数据绘制怎么办
# 思考题:如何根据画布大小绘制恰好填充屏幕的柱状图呢
count += 1
# 绘制图例, 可以封装为单独的函数
# 以下供有能力的学生选做
change_color('red')
rect(startx + 450, -50, 50, 20)
write('苹果')
change_color('green')
rect(startx + 450, -90, 50, 20)
write('桃子')
pu()
goto(-50, 140)
write('水果销量并列柱状图',align = 'center', font=('Arial', 28, 'normal'))
# print(help(write)) # 查看方法用法的函数
ht()
done()