Python 使用turtle模块绘制统计柱状图

【题目】使用turtle模块绘制词频统计结果,其中词频数据 wordFrequency = {"the":104, "a":63, "to":42, "of":42, "Kevin":36, "he":32, "you":28, "and":28, "is":27, "i":26}
以柱状图的形式展示统计结果。

今天在问答频道刷到的题,简单做了一遍画了两张图,分享给turtle入门者: 

import turtle
import time
t = turtle.Pen()

t.color("red")
t.pensize(3)
t.speed(0)

def Goto(x,y):
    t.penup()
    t.goto(x,y)
    t.pendown()
              
def rect(x,y,h,w=45):
    Goto(x,y)
    for i in range(2):
        t.forward(w)
        t.left(90)
        t.forward(h)
        t.left(90)
        t.fillcolor('red')

def main():
    start_x , start_y = -320, -200
    Goto(start_x , start_y)
    t.forward(630)
    for i,d in enumerate(wordFrequency.items()):
        rect(start_x + i*65, start_y ,d[1]*4 )
        tx = t.xcor()
        Goto(tx+(6-len(d[0]))*4, t.ycor()-25)
        t.write(d[0], font=('Arial',14,'normal'))
        Goto(tx + (8 if d[1]>100 else 12), t.ycor()+d[1]*4+30)
        t.write(d[1], font=('Arial',14,'normal'))

wordFrequency = {"the":104,"a":63,"to":42,"of":42,"Kevin":36,"he":32,"you":28,"and":28,"is":27,"i":26}
main()
time.sleep(3)

# 排序后再画
wordFrequency = { i:wordFrequency[i] for i in sorted(wordFrequency) }
t.clear()
main()

t.hideturtle()
turtle.mainloop()

单词排序后,再画一次:

附:常见命令:

命令说明
.forward() | fd( )向当前画笔方向移动distance像素长
.backward() | bd( ) | back( )向当前画笔相反方向移动distance像素长度
.right() | rt()顺时针移动degree°
.left() | lt()逆时针移动degree°
.pendown()移动时绘制图形,缺省时也为绘制
.penup()移动时不绘制图形,提起笔,用于另起一个地方绘制时用
.pensize(width)绘制图形时的宽度
.pencolor()画笔颜色
.fillcolor()绘制图形的填充颜色 fillcolor(colorstring)
.color()同时设置pencolor=color1, fillcolor=color2
.filling()返回当前是否在填充状态
.begin_fill()准备开始填充图形
.end_fill()填充完成
.setheading() | seth()设置当前朝向为某个角度
.position() | pos()返回乌龟当前的位置 (x,y)
.goto(x,y) | setpos() | setposion()将画笔移动到坐标为x,y的位置
.setx()、.sety()将当前x轴、y轴移动到指定位置
.xcor()、.ycor()返回画笔x、y坐标
.degrees() 将角度设置为度量单位,degrees(fullcircle=360.0 )
.radians() 将弧度设置为角度度量单位,相当于degrees(2*math.pi)
.home()设置当前画笔位置为原点,朝向东
.speed(speed)画笔绘制的速度,speed范围0~10
.circle()画圆,半径为正(负),表示圆心在画笔的左边(右边)画圆
.dot()使用给定颜色绘制给定直径大小的圆点 dot(size=None, *color)
.hide()隐藏箭头显示
.show()与hideturtle()函数对应
.clear()清空turtle窗口,但是turtle的位置和状态不会改变
.reset()清空窗口,重置turtle状态为起始状态
.undo()撤消(重复)最后一次动作,撤消操作数由取消缓冲区的大小决定
.isvisible()返回当前turtle是否可见
.stamp()复制乌龟形状的副本在当前canvas上,返回stamp_id
.clearstamp(stampid)删除给定stamp_id对应的标记
.clearstamps(n=None)删除标记的全部或前/后n个

 

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值