Anshul Rai
Anshul Rai

Reputation: 782

Getting the numpy array describing an arbitrary matplolib/seaborn plot

Is it possible to get the numpy array describing an arbitrary matplolib/seaborn plot without explicitly saving it as an image file and reading it?

For example, say I have the attached image which is a sns.kdeplot() of an array. Now, can I get the numpy array of this plot without first saving it to a file and reading it? Something like:

img = sns.kdeplot(arr)
img_arr = img.some_function() # Returns a numpy array describing the plot

enter image description here

Upvotes: 2

Views: 270

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

fig.canvas.tostring_rgb() would be helpful:

fig, ax = plt.subplots()
sns.kdeplot(arr, ax=ax)

img_arr = np.fromstring(fig.canvas.tostring_rgb(), 
                        dtype=np.uint8,
                        sep='')

Upvotes: 2

Related Questions