在pygame中使用matplotlib [英] Using matplotlib in pygame

查看:58
本文介绍了在pygame中使用matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个大问题-我想大多数人都不会喜欢这个问题,我可能会因为成为菜鸟而被炒鱿鱼,但无论如何这里还是会发生.

我正在尝试使用 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 -它们被称为后端" -但它没有使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆