绘制条形图并为其着色

问题描述 投票:0回答:1

您决定使用以下命令来跟踪每天每种类型披萨的销售数量: 堆积条形图。使用turtle模块绘制条形图,要求如下:

  • 每个条形包含四个矩形,代表每个矩形售出的披萨数量 类型。从下到上分别是大厚、大薄、中厚、中薄。
  • 每个矩形都有不同的颜色。
  • 绘制 x 轴和 y 轴。
  • 记录日期必须打印在栏下方。
  • 披萨的总数必须打印在吧台的顶部。
def draw_bar_chart(record_date, large_thick, large_thin, medium_thick, medium_thin): 
    # your logic here 
    # you don’t need to return anything 

这个问题我已经被困了两天了。我弄清楚了绘图部分,但填充颜色和其他对我来说有点太多了。有人可以帮助我吗?

图片:

enter image description here

python python-turtle
1个回答
0
投票

这是一种方法。

begin_fill()
end_fill()
的方式是使用
begin_fill()
,然后绘制一个闭合形状,然后使用
end_fill()
填充该形状。
.write()
功能可以为您绘制文字和数字。在这个程序中,有三只海龟:x 轴 (x)、y 轴 (y) 和我用来绘制图形的海龟 (t)。

#Setting up the turtles
import turtle
t = turtle.Pen()
x = turtle.Pen()
y = turtle.Pen()

#Creating the x axis
x.right(90)
x.penup()
x.forward(70)
x.pendown()
x.right(90)
x.forward(100)
x.left(180)
x.forward(300)

#Creating the y axis
y.right(90)
y.penup()
y.forward(70)
y.right(90)
y.forward(100)
y.pendown()
y.right(90)
y.forward(400)

#Moving the turtle down
t.right(90)
t.penup()
t.forward(100)
t.pendown()
t.left(90)

#Function for drawing the bars
def draw_bar_chart(record_date, large_thick, large_thin, medium_thick, medium_thin):
    #Writing the date at the bottom
    t.write(record_date)
    #Making sure you don't write over the date
    t.left(90)
    t.penup()
    t.forward(30)
    t.pendown()
    t.right(90)
    #Making the bars
    for count in range(0, 4):
        #Add your colors here
        color_list = ["red", "orange", "yellow", "green"]
        bars_list = [large_thick, large_thin, medium_thick, medium_thin]
        #Picking the color and starting the fill
        t.color(color_list[count])
        t.begin_fill()
        t.forward(40)
        t.left(90)
        #You may need to change the 10 here to a bigger or smaller number depending on your number
        t.forward(bars_list[count] * 10)
        t.left(90)
        t.forward(40)
        t.left(90)
        #You may need to change the 10 here to a bigger or smaller number depending on your number
        t.forward(bars_list[count] * 10)
        t.right(180)
        #You may need to change the 10 here to a bigger or smaller number depending on your number
        t.forward(bars_list[count] * 10)
        t.right(90)
        t.end_fill()
    #Writing the amount of pizzas
    t.color("black")
    t.write (large_thick + large_thin + medium_thick + medium_thin)
    t.hideturtle()

#Using the function with example parameters
draw_bar_chart("4/29/24", 10, 7, 6, 8)


或者,您可以使用 Python 内置函数

input()
向用户询问数字,但这只是一个基本版本。

© www.soinside.com 2019 - 2024. All rights reserved.