python - 在 pygame 中使用 matplotlib

标签 python python-3.x matplotlib pygame

我在这里有一个大问题 - 我想大多数人都不会喜欢这个问题,而且我可能会因为自己是菜鸟而受到批评,但无论如何,这里是。

我正在尝试使用 matplotlib 在我的 pygame 程序中实现条形图。我设法非常简单地做到了这一点,但没有使用 pygame。

我已经成功制作了一个条形图,但无法将其放入 pygame 中:

names = ['a', 'b', 'c']
values = [1, 10, 100]
plt.figure(1, figsize=(9, 3))
plt.bar(names, values)
plt.show()

我想在 pygame 中将其实现到我的游戏中,但老实说我不知道​​从哪里开始。这是下周到期的一个项目。谢谢。

最佳答案

matplotlib 默认使用 tkinter 显示图形。它还可以使用 PyQtwxPython - 它们被称为 “后端” - 但它没有使用 PyGame< 的方法 作为后端。

我发现(使用谷歌)的唯一内容是 example in PyGame wiki

它将 matplotlib 图形渲染为位图,然后将此位图转换为字符串,该字符串可用于创建带有图像的 Surface

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

enter image description here

奇怪的是,我不会使用 matplotlib 来创建图形 - 特别是它不是交互式的。在 PyGame 中创建自己的图表可以很容易。

关于python - 在 pygame 中使用 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093361/

相关文章:

python - 为什么在绘图标签中尝试使用 LaTeX 时出现错误

python - 将 matplotlib 图保存为数据库中的图像字段

python - 从格式化字符串打印 unicode

python - Python如何在远程机器上执行命令并等待执行完成?

python-3.x - 如何将单元格添加到 pd.DataFrame 但保留值的类型(np.uint64)?

python-3.x - 将 Unicode Escape 转换为希伯来语文本

python-3.x - 如何使用 Pandas 数据框中的纬度和经度计算距离?

python - Django:调试条目消失了

python - 相当于 asyncio.Queues 与 worker "threads"

python-3.x - python 3 散点图给出 "ValueError: Masked arrays must be 1-D"即使我没有使用任何掩码数组