Python乌龟创造横条

2024-10-01 15:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用Python库Turtle创建水平条形图。我怎么才能做到呢。我有一个垂直图形的示例,它工作得非常好,但是我需要对水平图形做同样的操作,并在水平方向显示值。在

这个url对垂直条形图有完美的帮助

http://students.washington.edu/xiongsy/zoekurt/blog/?p=399

我如何用这段代码达到我的要求。在


Tags: 代码http图形url示例水平blog方向
1条回答
网友
1楼 · 发布于 2024-10-01 15:41:26

您的垂直条形图示例不是很好的代码(有太多固定的假设)。不管怎样,我已经完成了一个粗略的工作,将x和y轴反转为水平条形图示例:

from turtle import Turtle, Screen

FONT_SIZE = 12
FONT = ("Arial", FONT_SIZE, "normal")

COLORS = ['#CC9933', '#6699CC', '#CC3399', '#996633', '#336699', '#0099CC', '#FF9999', '#CC0066', '#99CC00', '#CC3399', '#009933']

print("Welcome to the Turtle Charter!")

### Prompt for input ###

title = input("What is the title of your chart? ")

n = 1
data = {}

while True:
    label = input('Input data label {}: '.format(n))
    if label == '':
        break

    while True:
        value = input('Input data value {}: '.format(n))

        try:
            value = float(value)
            break
        except ValueError:
            print('Please enter only numeric value.')

    data[label] = value
    n += 1

print("Generating graph...")

### Create and Setup the Window ###
xmax = max(data.values())
window = Screen()
window.title(title)
height = 130 * (len(data) + 1)  # (the space between each bar is 30, the width of each bar is 100)
window.setup(600, height)  # specify window size (width is 600)

turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.penup()
turtle.setpos(-225, -(height / 2) + 50)
turtle.pendown()

# draw x-axis and ticks
xtick = 400 / 7

for i in range(1, 8):
    turtle.forward(xtick)
    xv = float(xmax / 7 * i)
    turtle.write('%.1f' % xv, move=False, align="center", font=FONT)
    turtle.right(90)
    turtle.forward(10)
    turtle.backward(10)
    turtle.left(90)

turtle.setpos(-225, -(height / 2) + 50)
turtle.left(90)

# draw bar and fill color
pixel = xmax / 400
recs = []  # bar height
for value in data.values():
    recs.append(value / pixel)

for i, rec in enumerate(recs):
    turtle.color('black')
    turtle.forward(30)
    turtle.right(90)
    turtle.begin_fill()
    turtle.forward(rec)
    turtle.left(90)
    turtle.forward(50 - FONT_SIZE/2)
    turtle.write('  ' + str(rec * pixel), move=False, align="left", font=FONT)
    turtle.forward(50 + FONT_SIZE/2)
    turtle.left(90)
    turtle.forward(rec)
    turtle.color(COLORS[i % len(COLORS)])
    turtle.end_fill()
    turtle.right(90)

turtle.setpos(-225, -(height / 2) + 50)
turtle.color('black')

# draw y-axis and labels
turtle.pendown()

for key in data:
    turtle.forward(30)
    turtle.forward(10)
    turtle.write('  ' + key, move=False, align="left", font=FONT)
    turtle.forward(90)

turtle.forward(30)

### Tell the window to wait for the user to close it ###
window.mainloop()

enter image description here

相关问题 更多 >

    热门问题