|
发表于 2023-3-31 20:31:10
|
显示全部楼层
用 turtle 也可以,不过不好看
直方图:import turtle
# 各行星的质量倍数
mass_ratios = [0.166, 0.377, 0.638, 0.91, 1.0, 1.886, 2.530, 8.871]
# 各行星的名字
planet_names = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
# 计算物品在各行星上的重量
weights = [r * 100 for r in mass_ratios]
# 创建Turtle对象并设置属性
t = turtle.Turtle()
t.speed(0)
t.pensize(2)
# 绘制直方图
for i, w in enumerate(weights):
t.penup()
t.goto(i * 50 - 200, 0)
t.pendown()
t.left(90)
t.forward(w)
t.write(f"{w:.2f}")
t.right(90)
t.forward(20)
t.right(90)
t.forward(w)
t.left(90)
# 绘制横坐标和纵坐标
t.penup()
t.goto(-250, -150)
t.pendown()
t.forward(500)
t.left(180)
t.forward(10)
t.right(90)
t.forward(300)
t.write('Weight (kg)')
t.penup()
t.goto(-200, -170)
t.write('Planets')
for i, p in enumerate(planet_names):
t.penup()
t.goto(i * 50 - 200, -200)
t.write(p)
# 点击屏幕关闭窗口
turtle.done()
折线图:import turtle
# 各行星的质量倍数
mass_ratios = [0.166, 0.377, 0.638, 0.91, 1.0, 1.886, 2.530, 8.871]
# 各行星的名字
planet_names = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
# 计算物品在各行星上的重量
weights = [r * 100 for r in mass_ratios]
# 创建Turtle对象并设置属性
t = turtle.Turtle()
t.speed(0)
t.pensize(3)
# 绘制折线图
for i, w in enumerate(weights):
t.penup()
t.goto(i * 50 - 200, w)
t.pendown()
t.dot(10)
t.write(f"{w:.2f}")
if i < len(weights) - 1:
next_w = weights[i+1]
t.goto((i+1) * 50 - 200, next_w)
# 绘制横坐标和纵坐标
t.penup()
t.goto(-250, -150)
t.pendown()
t.forward(500)
t.left(180)
t.forward(10)
t.right(90)
t.forward(300)
t.write('Weight (kg)')
t.penup()
t.goto(-200, -170)
t.write('Planets')
for i, p in enumerate(planet_names):
t.penup()
t.goto(i * 50 - 200, -200)
t.write(p)
# 点击屏幕关闭窗口
turtle.done()
|
|