I have an AI for a game in Pygame and I want to create a chart to follow the evolution.
I need only the Gen on X-axis and Points on the Y-axis.
I have tried this but I don't know how to make it fit on the surface in the game, and not pop out as an individual window(which will eventually stop the game)
import matplotlib.pyplot as plt
plt.plot(Generation=[], Points=[])
plt.title('Points per Generation')
plt.xlabel('Generation')
plt.ylabel('Points')
plt.show()
Any ideas?
One approach is to render and store the pyplot
to a Buffered Steam . This stream can be loaded into a pygame.Surface
object with 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')
Minimal example:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.