2

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

Anshul Rai
  • 772
  • 7
  • 21

1 Answers1

2

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='')
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74