I'm just starting to use pyglet, and I'm trying to develop a visual rendering for a reinforcement learning application using gym.
I would need to integrate a graph generated with matplolib or something else to my window. I found some sample code that does what I want, but it doesn't seem to work since python 3.
There seems to be a problem with the StringIO class of io that I declare at line 15 and use at line 16. I'am not sure of what it is exactly though.
import pyglet
import io
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
def render_figure(fig):
w, h = fig.get_size_inches()
dpi_res = fig.get_dpi()
w, h = int(np.ceil(w * dpi_res)), int(np.ceil(h * dpi_res))
canvas = FigureCanvasAgg(fig)
pic_data = io.StringIO()
canvas.print_raw(pic_data, dpi=dpi_res)
return pyglet.image.ImageData(w, h, "RGBA", pic_data.getvalue(), -4 * w)
def draw_figure(fig):
X = np.linspace(-6, 6, 1024)
Y = np.sinc(X)
ax = fig.add_subplot(111)
ax.plot(X, Y, lw=2, color="k")
window = pyglet.window.Window(fullscreen=True)
dpi_res = min(window.width, window.height) / 10
fig = Figure((window.width / dpi_res, window.height / dpi_res), dpi=dpi_res)
draw_figure(fig)
image = render_figure(fig)
@window.event
def on_draw():
window.clear()
image.blit(0, 0)
pyglet.app.run()
You have to use the FigureCanvasAgg.print_to_buffer() method:
def render_figure(fig):
canvas = FigureCanvasAgg(fig)
data, (w, h) = canvas.print_to_buffer()
return pyglet.image.ImageData(w, h, "RGBA", data, -4 * w)
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