I have a big question here - one that I imagine the majority of people will not like and I will probably be flamed for being a noob but here goes anyway.
I am trying to use matplotlib to implement a barchart into my pygame program. I managed to do it pretty simply but not using pygame.
I have managed to make a bar chart but I am not able to put it into pygame:
names = ['a', 'b', 'c']
values = [1, 10, 100]
plt.figure(1, figsize=(9, 3))
plt.bar(names, values)
plt.show()
I want to implement this to my game in pygame but I honestly have no idea where to start. It is for a project due next week. Thanks.
Matplotlib is a cross-platform, data visualization and graphical plotting library for Python and its numerical extension NumPy. As such, it offers a viable open source alternative to MATLAB. Developers can also use matplotlib's APIs (Application Programming Interfaces) to embed plots in GUI applications.
The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook.
matplotlib
as default uses tkinter
to display graph. It can also use PyQt
or wxPython
- they are called "backends"
- but it doesn't have methods to use PyGame
as backend.
The only what I found (using Google) is example in PyGame wiki
It renders matplotlib graph to bitmap and then converts this bitmap to string which can be used to create Surface
with image.
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
Fankly I wouldn't use matplotlib to create graph - escpecially it is not interactive. It could be easy to create own graph in PyGame.
You might want to take a look to this library that attempts to create a proper pygame backend for matplotlib. https://pypi.org/project/pygame-matplotlib/
It is under beta developpement for the moment, but looks promising.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With