pygame 画三条不同颜色的折线图
时间: 2023-10-19 09:15:24 浏览: 69
绘制折线图
下面是一个简单的示例程序,绘制三条不同颜色的折线图:
```python
import pygame
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
size = (400, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("折线图")
# 定义颜色
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设定数据
data1 = [10, 50, 30, 80, 60]
data2 = [20, 40, 70, 90, 50]
data3 = [30, 60, 50, 40, 70]
# 设定坐标轴起始点
x0 = 50
y0 = 350
# 设定坐标轴长度
x_length = 300
y_length = 300
# 设定坐标轴间隔
x_gap = x_length // (len(data1) - 1)
y_gap = y_length // 10
# 绘制坐标轴
pygame.draw.line(screen, BLACK, (x0, y0), (x0 + x_length, y0), 2)
pygame.draw.line(screen, BLACK, (x0, y0), (x0, y0 - y_length), 2)
# 绘制坐标轴标签
font = pygame.font.Font(None, 20)
for i in range(len(data1)):
text = font.render(str(i+1), True, BLACK)
screen.blit(text, (x0 + i*x_gap - 10, y0 + 10))
for i in range(11):
text = font.render(str(i*10), True, BLACK)
screen.blit(text, (x0 - 30, y0 - i*y_gap - 10))
# 绘制数据
for i in range(len(data1)-1):
x1 = x0 + i*x_gap
x2 = x0 + (i+1)*x_gap
y1 = y0 - data1[i]*y_gap//10
y2 = y0 - data1[i+1]*y_gap//10
pygame.draw.line(screen, RED, (x1, y1), (x2, y2), 2)
for i in range(len(data2)-1):
x1 = x0 + i*x_gap
x2 = x0 + (i+1)*x_gap
y1 = y0 - data2[i]*y_gap//10
y2 = y0 - data2[i+1]*y_gap//10
pygame.draw.line(screen, GREEN, (x1, y1), (x2, y2), 2)
for i in range(len(data3)-1):
x1 = x0 + i*x_gap
x2 = x0 + (i+1)*x_gap
y1 = y0 - data3[i]*y_gap//10
y2 = y0 - data3[i+1]*y_gap//10
pygame.draw.line(screen, BLUE, (x1, y1), (x2, y2), 2)
# 更新屏幕
pygame.display.flip()
# 游戏循环
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 退出 Pygame
pygame.quit()
```
在这个示例程序中,我们首先定义了三组数据,分别对应三条折线图。然后,我们设定了坐标轴起始点、长度和间隔,并根据这些参数绘制了坐标轴和标签。最后,我们使用 `pygame.draw.line` 函数绘制了三条折线图。
在绘制折线图时,我们使用了数据和坐标轴间隔来计算每个数据点的坐标,然后在相邻两个点之间绘制一条直线。我们使用不同的颜色来区分不同的折线图。
阅读全文