【问题标题】:How can build a bar graph in turtle using dictionaries?如何使用字典在海龟中构建条形图?
【发布时间】:2020-11-22 02:10:10
【问题描述】:

我只是想知道如何制作一个条形图,它使用字典中的键对来使用它作为 x 轴和键值来绘制图表。

例如:dic = {'0-10': 24, '10-20': 20, '20-30': 22, '30-40': 27, '40-50': 150, '50-60': 0, '60-70': 231, '70-80': 467, '80-90': 443, '90-100': 86}

我希望将“0-10”作为 x 轴,将数字作为条形的高度。这是我的代码,但我找不到为它绘制 x 轴的内容。 y 轴也将始终为 100。

import turtle
from main import value_pairs, key_values

# Basic function to draw "bar graph", it takes the height as prameter
def drawBar(t, height):
    t.begin_fill()
    t.left(90)
    t.forward(height)
    t.write(str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)
    t.end_fill()


xs = value_pairs
maxheight = max(xs)
numbars = len(xs)
border = 5

wn = turtle.Screen()
wn.setworldcoordinates(0-border, 0-border, 40*numbars+border, maxheight+border)
wn.bgcolor("white")

t = turtle.Turtle()
t.color("black")
t.fillcolor("white")
t.pensize(3)


for x in value_pairs:
    drawBar(t, x)

【问题讨论】:

    标签: python graph turtle-graphics python-turtle


    【解决方案1】:

    我已经修改了您的尝试,大致按照您的描述进行,并从您发布的代码中填补了缺失的部分:

    from turtle import Screen, Turtle
    
    FONT_HEIGHT = 18
    FONT = ('Arial', FONT_HEIGHT, 'normal')
    BORDER = FONT_HEIGHT
    
    def drawBar(t, datum):
        label, height = datum
    
        t.left(90)
    
        t.begin_fill()
        t.forward(height)
        t.right(90)
        t.forward(20)
        if height > FONT_HEIGHT:
            t.write(height, align="center", font=FONT)
        t.forward(20)
        t.right(90)
        t.forward(height)
        t.end_fill()
    
        t.left(90)
    
        t.backward(40)
        t.forward(20)
        t.write(label, align="center", font=FONT)
        t.forward(20)
    
    data = {
        '0-10': 24,
        '10-20': 20,
        '20-30': 22,
        '30-40': 27,
        '40-50': 150,
        '50-60': 0,
        '60-70': 231,
        '70-80': 467,
        '80-90': 443,
        '90-100': 86
    }
    
    maxheight = max(data.values())
    numbars = len(data)
    
    screen = Screen()
    screen.setworldcoordinates(-BORDER, -BORDER, 40 * numbars + BORDER, maxheight + BORDER)
    
    turtle = Turtle()
    turtle.speed('fastest')  # because I have no patience
    turtle.fillcolor('white')
    turtle.pensize(3)
    
    for datum in data.items():
        drawBar(turtle, datum)
    
    turtle.hideturtle()
    screen.exitonclick()
    

    Matplotlib 是使用 Python 进行数据可视化的黄金标准,但使用 turtle 尝试这些东西总是很有趣,以便更好地了解绘图所涉及的内容。

    警告:这种方法假设有序字典——这在历史上不是一个安全的假设。

    【讨论】:

    • 太好了,现在把它放在一个类中,并使它的垃圾箱可以有不同的宽度...... ;-) 我喜欢有人使用错误的工具过度杀死答案! +1
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2018-05-30
    • 2014-12-21
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多