python绘制柱状统计图_2018-08-04 Python Turtle绘制简易柱状统计图

本文通过Python的turtle模块,演示了如何绘制柱状统计图。首先定义了初始化数据的函数,生成随机数据模拟苹果和桃子的数量,然后利用turtle进行绘制,包括红色的苹果柱和绿色的桃子柱,并在右侧绘制了图例。
摘要由CSDN通过智能技术生成

在高年级小学数学课中,有关于柱状图的内容,现在用Python turtle来实现

b58683032521

柱状图效果

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值