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?