在 pygame 中使用 matplotlib [英] Using matplotlib in pygame
问题描述
我在这里有一个大问题 - 我想大多数人不会喜欢这个问题,我可能会因为是菜鸟而受到抨击,但无论如何还是要问.
我正在尝试使用 matplotlib 在我的 pygame 程序中实现条形图.我设法很简单地做到了,但没有使用 pygame.
我已经设法制作了一个条形图,但我无法将其放入 pygame:
names = ['a', 'b', 'c']值 = [1, 10, 100]plt.figure(1, figsize=(9, 3))plt.bar(名称,值)plt.show()
我想在 pygame 中将其实现到我的游戏中,但老实说我不知道从哪里开始.这是下周到期的项目.谢谢.
matplotlib
默认使用 tkinter
来显示图形.它还可以使用 PyQt
或 wxPython
- 它们被称为 backends"
- 但它没有使用 PyGame 的方法
作为后端.
我发现的唯一内容(使用 Google)是
坦率地说,我不会使用 matplotlib 来创建图形 - 特别是它不是交互式的.在 PyGame 中创建自己的图形很容易.
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
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.
这篇关于在 pygame 中使用 matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!