我在 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()
有什么想法吗?
最佳答案
一种方法是渲染并存储 pyplot
到 Buffered 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/