Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The seaborn not saving the whole figure but only part of it

I used seaborn in python to plot and save a figure. In the jupyter notebook it looks like this.

Whole figure

But when I use the following code to save the figure, it shows like this. Only part of it

I don't know why. This is my python code.

whole_pt = whole_rules_df.pivot_table(index='whole_rules_from', columns='whole_rules_to', values='whole_rules_value', aggfunc=np.sum)
f, ax = plt.subplots(figsize=(12,8))
one_heat = sns.heatmap(whole_pt, fmt="d",cmap='YlGnBu', ax=ax,vmin=0,vmax=1)
one_heat.get_figure().savefig('whole_rules.jpg')
like image 478
Xudong Shao Avatar asked Oct 25 '25 23:10

Xudong Shao


1 Answers

The matplotlib figure itself is the figure which is cropped. However, when a matplotlib figure is displayed in the inline backend with jupyter, what is shown is a saved png version of the figure. This "saving" is performed using the bbox_inches="tight" option, which enlarges or crops the saved region to the content of the figure.

To achieve the same when manually saving the figure, this option also has to be included,

fig.savefig("filename.png", bbox_inches="tight")

Alternatively it could be useful to directly produce a figure with the content fitting into is. This can be done using the fig.subplots_adjust() method or by calling fig.tight_layout().

like image 110
ImportanceOfBeingErnest Avatar answered Oct 27 '25 13:10

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!