【问题标题】:Turtle: fill bars in chart based on heightTurtle:根据高度填充图表中的条形图
【发布时间】:2014-05-09 18:10:20
【问题描述】:

Python 中的 Turtles 模块:

我想用基于高度的颜色填充条形。下面的代码正确绘制了条形图,但颜色与 if 语句不匹配。怎么了?

它正在填充: 【黑、绿、黄、红、红、黄、红】

应该是: [绿、黄、红、红、黄、红、红]

import turtle

def drawBar(t, height):
    """ Get turtle t to draw one bar, of height. """
    t.begin_fill()               # start filling this shape
    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()                 # stop filling this shape

def fillColor(t,height):
    drawBar(t,height)
    if height >=200:
        t.fillcolor("red")
    elif height >= 100 and height < 200:
        t.fillcolor("yellow")
    else:
        t.fillcolor("green")


xs = [48,117,200,240,160,260,220]  # here is the data
maxheight = max(xs)
numbars = len(xs)
border = 10

tess = turtle.Turtle()           # create tess and set some attributes
#tess.color("blue")
#tess.fillcolor("red")
tess.pensize(3)


wn = turtle.Screen()             # Set up the window and its attributes
wn.bgcolor("lightgreen")
wn.setworldcoordinates(0-border,0-border,40*numbars+border,maxheight+border)


for i in xs:
    fillColor(tess,i)

wn.exitonclick()

【问题讨论】:

    标签: python function fill turtle-graphics


    【解决方案1】:

    您需要在选择颜色之后绘制列:

    def fillColor(t,height):
        if height >=200:
            t.fillcolor("red")
        elif height >= 100 and height < 200:
            t.fillcolor("yellow")
        else:
            t.fillcolor("green")
        drawBar(t,height)
    

    (第一列是黑色的,因为那是默认的填充颜色。)

    【讨论】:

    • 谢谢!说得通。新手,现在可以睡得更好...已解决。
    猜你喜欢
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多