python - 如何在 PyGame 中集成折线图查看器?

标签 python matplotlib pygame pygame-surface

我在 Pygame 中有一个游戏的 AI,我想创建一个图表来跟踪演变。

我只需要 X 轴上的 Gen 和 Y 轴上的点。

我已经尝试过这个,但我不知道如何让它适合游戏的表面,而不是作为单独的窗口弹出(这最终会停止游戏)

import matplotlib.pyplot as plt

plt.plot(Generation=[], Points=[])
    plt.title('Points per Generation')
    plt.xlabel('Generation')
    plt.ylabel('Points')
    plt.show()

有什么想法吗?

最佳答案

一种方法是渲染并存储 pyplotBuffered Steam 。该流可以加载到 pygame.Surface对象 pygame.image.load :

plot_stream = io.BytesIO()
plt.savefig(plot_stream, formatstr='png')
plot_stream.seek(0)

plot_surface = pygame.image.load(plot_stream, 'PNG')

最小示例:

import matplotlib.pyplot as plt
import pygame
import io

plt.plot(Generation=[], Points=[])
plt.title('Points per Generation')
plt.xlabel('Generation')
plt.ylabel('Points')

plot_stream = io.BytesIO()
plt.savefig(plot_stream, formatstr='png')
plot_stream.seek(0)

pygame.init()
plot_surface = pygame.image.load(plot_stream, 'PNG')

window = pygame.display.set_mode(plot_surface.get_size())
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    window.fill(0)
    window.blit(plot_surface, (0, 0))
    pygame.display.flip()

pygame.quit()
exit()

关于python - 如何在 PyGame 中集成折线图查看器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70493951/

相关文章:

python - 如何在 pygame 中获取两个碰撞的 Sprite 对象?

python - 使用 matlab 运行 python 脚本

python - 子目录未显示在 django 管理页面中

python - 使用 numpy 将自定义颜色分配给集群

python - 在 Python 中绘制网络/关系/连接类型图

python - 如何将 Unicode 标题传递给 matplotlib?

python - 我如何使用二进制列表在 PyGame 中绘制正方形?

python - 是否可以在pygame中使用简单的旋转矩阵来模拟圆形轨道?

python函数确定一个数字属于给定数字列表的统计可能性

python - 在 Pandas 数据帧上应用 Savitzky-Golay 过滤器