3

I have a dict of numbers (prices exactly)/each month:

{'2018-05-26': Decimal('7334.1638'), '2018-05-27': Decimal('7344.9675'), '2018-05-28': Decimal('7105.6725')}

I can easily plot this using plotly and the plot looks like this: Plot

I want this graph to show as a drawing in pygame. I got several examples on how to show matplotlib data in pygame but those just copy/paste the plot and you can't interact with the environment. What I want to do is make this plot the playing environment in pygame.

Lets say if I want a car to run on this plot like a hill. Also as my list is dynamic so I need it to be real-time. Any advice on how to achieve this would be helpful.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

0

I used this method from pygame wiki - http://www.pygame.org/wiki/MatplotlibPygame It renders grapgh from matplotlib into bitmap, then converts it into string, and then uses this string to create surface with image in pygame.

import matplotlib
matplotlib.use("Agg")

import matplotlib.backends.backend_agg as agg


import pylab

fig = pylab.figure(figsize=[4, 4], # Inches
                   dpi=100,        # 100 dots per inch, so the resulting buffer is 400x400 pixels
                   )
ax = fig.gca()
ax.plot([1, 2, 4])

canvas = agg.FigureCanvasAgg(fig)
canvas.draw()
renderer = canvas.get_renderer()
raw_data = renderer.tostring_rgb()

import pygame
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((600, 400), DOUBLEBUF)
screen = pygame.display.get_surface()

size = canvas.get_width_height()

surf = pygame.image.fromstring(raw_data, size, "RGB")
screen.blit(surf, (0,0))
pygame.display.flip()

crashed = False
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
Tikrong
  • 29
  • 4