0

I'm writing a script where I want to programmatically extract a matplotlib figure as a ndarray of pixel values. To achieve this I'm using the fig.canvas.buffer_rgba() method. I've noticed this works when I use the pyplot functional API but not the object oriented API.

This works:

fig = plt.figure()
plt.plot(x, y)
fig.canvas.draw()
im = np.asarray(fig.canvas.buffer_rgba())  # works

But when I use the object-oriented API fig.canvas.draw() is just a black image:

fig, ax = plt.subplots()
ax.plot(x, y)
fig.canvas.draw()
im = np.asarray(fig.canvas.buffer_rgba())  # gives black image (array of zeros)

Ultimately I'm wanting to use pandas DataFrame.plot(), e.g.:

fig, ax = plt.subplots()
df.plot(**kwargs, ax=ax)
im = np.asarray(fig.canvas.buffer_rgba())  

Any ideas why this isn't working?

  • Does [this question](https://stackoverflow.com/questions/35355930/matplotlib-figure-to-image-as-a-numpy-array) answers yours? Using `im = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')` instead of `im = np.asarray(fig.canvas.buffer_rgba())` should do the trick. – thmslmr Mar 03 '23 at 16:25

0 Answers0