seaborn 不会保存整个图形,而是保存其中的一部分

Xud*_*hao 1 python matplotlib seaborn

我在 python 中使用 seaborn 来绘制和保存图形。在 jupyter notebook 中,它看起来像这样。

全图

但是当我使用下面的代码来保存图形时,它是这样显示的。 只是其中的一部分

我不知道为什么。这是我的python代码。

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')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 9

matplotlib 图形本身就是被裁剪的图形。但是,当使用 jupyter 在内联后端中显示 matplotlib 图时,显示的是该图的已保存 png 版本。这种“保存”是使用bbox_inches="tight"选项执行的,该选项将保存的区域放大或裁剪为图形的内容。

为了在手动保存图形时实现相同的效果,还必须包含此选项,

fig.savefig("filename.png", bbox_inches="tight")
Run Code Online (Sandbox Code Playgroud)

或者,直接生成内容适合 is 的图形可能很有用。这可以使用fig.subplots_adjust()方法或通过调用来完成fig.tight_layout()