海龟:根据高度填充图表中的条形
Python中的Turtles模块:
我想根据高度给条形图填充颜色。下面的代码可以正确绘制条形图,但颜色和我的条件判断不一致。哪里出了问题呢?
现在填充的颜色是: [黑色, 绿色, 黄色, 红色, 红色, 黄色, 红色]
但我希望是: [绿色, 黄色, 红色, 红色, 黄色, 红色, 红色]
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()
1 个回答
0
你需要在选择颜色 之后 来绘制这列:
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)
(第一列是黑色的,因为黑色是默认的填充颜色。)