2

I'm trying to create a heatmap with seaborn. I want to save the heatmap plot as an image without the colorbar and without the white space surrounding the plot to use it for further analysis.

my_np = np.array([[1,2,4,2,3,5,6,10], [1,3,8,2,9,5,6,9],[1,4,4,6,7,5,8,1],[2,0,3,5,7,8,9,1], [2,9,4,3,7,5,8,8], [3,9,4,3,7,5,8,8],[3,9,4,3,7,5,8,8],[3,1,4,4,0,5,8,8],[3,9,0,3,7,5,8,8]])

sns.heatmap(my_np)

I tried the bbox_inches='tight', pad_inches=0 but it didn't work

Bellow an example on my real array enter image description here

I'm trying to have enter image description here

Noura
  • 474
  • 2
  • 11
  • 2
    What white borders are you referring to (perhaps a picture would help here)? As for the colorbar, add the parameter `cbar = False` to your `sns.heatmap` line. – m13op22 Jul 15 '20 at 21:48
  • Try to create the heatmap without the colorbar, and turn the axes off: `ax = sns.heatmap(my_np, cbar=False); ax.axis('off')` – JohanC Jul 15 '20 at 22:20
  • I edited my post. I want to remove the white space surrounding the plot – Noura Jul 15 '20 at 22:22
  • Does this answer your question? [Removing white space around a saved image in matplotlib](https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib) – JohanC Jul 15 '20 at 22:43
  • I tried it but it din't work, the used plt.imshow must be applied to an array-like or a PIL image not to a matplotlib plot – Noura Jul 15 '20 at 22:50

1 Answers1

2

If you set bbox_inches='tight' and pad_inches=0.01 as saving parameters, images without white edges will be saved.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()

my_np = np.array([[1,2,4,2,3,5,6,10], [1,3,8,2,9,5,6,9],[1,4,4,6,7,5,8,1],[2,0,3,5,7,8,9,1], [2,9,4,3,7,5,8,8], [3,9,4,3,7,5,8,8],[3,9,4,3,7,5,8,8],[3,1,4,4,0,5,8,8],[3,9,0,3,7,5,8,8]])

ax = sns.heatmap(my_np, cbar=False)
ax.axis('off')

plt.savefig('./nowhitespace.png', bbox_inches='tight', pad_inches=0.01)
plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32