作为一种实践,我使用python中的turtle模块生成条形图。
使用以下代码并获得了简单的条形图,但是有一个我想改进的细节。
import turtle
def generaVentana():
w = turtle.Screen()
w.title("Ejercicio 7, 8")
w.bgcolor("lightgreen")
return w
def generaTortuga():
t = turtle.Turtle()
t.pensize(2)
return t
wn = generaVentana()
tess = generaTortuga()
xs = [48, 117, -200, 240, 160, 260, 220]
def draw_bar(t, height):
if (height < 100):
t.color("black", "green")
elif (height >= 100 and height < 200):
t.color("black", "yellow")
elif (height >= 200):
t.color("black", "red")
t.begin_fill()
t.left(90)
t.forward(height)
t.right(90)
t.write(" " + str(height))
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill()
t.penup()
t.forward(10)
t.pendown()
for v in xs:
draw_bar(tess, v)
wn.mainloop()
使用负值定义条形时会生成,但是使用write()函数打印的条形的大小会显示在条形的内部。
但是我希望它显示在栏的外部。
,并尝试在代码中使用换行符“ \ n”与返回的高度字符串的值连接在一起,但是它不起作用。
有一些方法可以强制这种行为,谢谢。
答案 0 :(得分:1)
逻辑是,文本的当前乌龟位置写为
当您处于负面状态时,您需要在书写文字之前向下移动一些额外的距离向下。在条形图操作的中间这样做有点麻烦,因此我将标签打印与条形图分开,像这样:
def draw_bar(t, height):
if height < 100:
t.color("black", "green")
elif height >= 100 and height < 200:
t.color("black", "yellow")
else: # no need to put a condition here
t.color("black", "red")
# add this block:
t.left(90)
p = t.position()
t.penup()
# when height is negative, move 14 more in that downward direction.
t.forward(height - 14 * int(height < 0))
t.write(" " + str(height))
t.goto(p)
t.pendown()
# end of added block
t.begin_fill()
# removed: t.left(90)
t.forward(height)
t.right(90)
# removed: t.write(" " + str(height))
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill()
t.penup()
t.forward(10)
t.pendown()
顺便说一句:不需要最后的elif
,您只需执行else
。另外,您不需要在if
条件周围加上括号。
您可能还想考虑将打印的文本居中居中,使之居中。更改此行:
t.write(" " + str(height))
收件人:
t.right(90)
t.forward(20) # move to (horizontal) center of bar
t.write(str(height), align="center")
t.left(90)
答案 1 :(得分:1)
我将控制您的字体大小,以便您可以相对于当前字体移动,而不用估计默认字体:
from turtle import Screen, Turtle
xs = [48, 117, -200, 240, 160, 260, 220]
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'normal')
def generaVentana():
screen = Screen()
screen.title("Ejercicio 7, 8")
screen.bgcolor("lightgreen")
return screen
def generaTortuga():
turtle = Turtle()
turtle.pensize(2)
turtle.penup()
return turtle
def draw_bar(t, height):
if height < 100:
t.fillcolor("green")
elif 100 <= height < 200:
t.fillcolor("yellow")
else:
t.fillcolor("red")
t.left(90)
t.pendown()
t.begin_fill()
t.forward(height)
t.right(90)
t.forward(20)
if height < 0:
t.penup()
position = t.position() # save
t.sety(t.ycor() - FONT_SIZE - t.pensize())
t.write(height, align='center', font=FONT)
if height < 0:
t.setposition(position) # restore
t.pendown()
t.forward(20)
t.right(90)
t.forward(height)
t.end_fill()
t.penup()
t.left(90)
t.forward(10)
wn = generaVentana()
tess = generaTortuga()
for value in xs:
draw_bar(tess, value)
wn.mainloop()