0

I have a code that looks like this:

corr = sdf.corr(method="spearman")
corr.style.background_gradient(cmap='coolwarm')

I have an output of correlation graph. I saw online to use this code to save it as image

fig, ax = plt.subplots()
plt.figure(figsize = (16,8))
sns.heatmap(sdf.corr(method='spearman'), annot=True, fmt='.4f', 
            cmap=plt.get_cmap('coolwarm'), cbar=False, ax=ax)
ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal")
plt.savefig('result.png', bbox_inches='tight', pad_inches=0.0)

But this clogs the output like this: enter image description here

How do I save this?

Edit:

Tried the answer below and it is showing this.

enter image description here

Mubashir Raza
  • 143
  • 1
  • 6
  • Check this answer and see if it helps you out https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels – Oddity Oct 03 '20 at 05:49

3 Answers3

0

Try this:

plt.savefig("result.png", dpi = 100)
ah bon
  • 9,293
  • 12
  • 65
  • 148
almo
  • 561
  • 2
  • 16
0

You can make use of the following to save your image.

plt.matshow(data.corr())
plt.savefig('corr.png', dpi=300)

I would suggest you increase the figure size and then try to save it as an image. In your case, one possible reason can be that you are making use of sns.heatmap() and that is the reason it is not saving.

Amit Pathak
  • 1,145
  • 11
  • 26
0
  1. fig and ax are not defined correctly. plt.subplots() and plt.figure() should not be simultaneously called. In your code, it is recommended that plt.figure(figsize = (16,8)) be deleted and the parameter figsize = (16,8) be moved to plt.subplots.
fig, ax = plt.subplots(figsize = (16,8))
sns.heatmap(sdf.corr(method='spearman'), annot=True, fmt='.4f', 
            cmap=plt.get_cmap('coolwarm'), cbar=False, ax=ax)
ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal")
plt.savefig('result.png', bbox_inches='tight', pad_inches=0.0)
  1. The figure size might be too small for the numbers to display. Try enlarge the figsize like
fig, ax = plt.subplots(figsize = (20, 10))
sns.heatmap(sdf.corr(method='spearman'), annot=True, fmt='.4f', 
            cmap=plt.get_cmap('coolwarm'), cbar=False, ax=ax)
ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal")
plt.savefig('result.png', bbox_inches='tight', pad_inches=0.0)

enter image description here

Cheng
  • 301
  • 2
  • 9
  • Please check the answer – Mubashir Raza Oct 04 '20 at 03:56
  • Incomplete heatmap was a bug I came across before, which was caused by incompatible versions between seaborn and matplotlib. Update them both to the lastest versions and the output will hopefully be fine. – Cheng Oct 05 '20 at 06:39