plt.savefig不保存图像

2024-06-24 12:18:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个代码:

heatmap = sns.clustermap(corrMatrix, row_colors=row_colors, 
                         #metric='correlation',
                         #method='single',
                         xticklabels=True, yticklabels=True, 
                         cmap='coolwarm', annot=False, fmt=".2f", 
                         #annot_kws={'size':6}, square=False,
                         dendrogram_ratio=(.1, .2),
                         cbar_pos=(1, .2, .03, .4))

loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=90)
heatmap.set_yticklabels(labels, rotation=0)
bottom, top = heatmap.get_ylim()
heatmap.set_ylim(bottom + 0.5, top -0.5)

heatmap.savefig(r'similarity' + '.svg', format='svg', dpi=600, bbox_inches = "tight" )

工作正常,但不保存图形,仅使用我尝试使用的plt.savefig()figure = heatmap.get_figure()的这种类型的绘图(clustermap),什么都没有


1条回答
网友
1楼 · 发布于 2024-06-24 12:18:15

您的代码在heatmap.set_xticklabels(...)行上崩溃

AttributeError: 'ClusterGrid' object has no attribute 'set_xticklabels'

sns.clustermap是一个figure-level function。它返回一个ClusterGrid(轴级函数返回一个matplotlibax

在seaborn的文档中,调用图形级函数g =(其中g是“grid”的第一个字母)的返回值是一种习惯。如果开始给这些变量起不同的名字,很容易在seaborn的文档中迷失方向,也很容易在尝试使用matplotlib函数进行进一步自定义时迷失方向

以下代码显示了预期的命名约定和旋转标签的预期方式。(我不理解更改ylim的原因,可能这与an old problem with matplotlib有关?这样更改ylim会使绘图看起来出错。)

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

g = sns.clustermap(np.random.rand(10, 10), row_colors=plt.cm.tab10.colors,
                   xticklabels=True, yticklabels=True,
                   cmap='coolwarm', annot=False, fmt=".2f",
                   dendrogram_ratio=(.1, .2),
                   cbar_pos=(1, .2, .03, .4))

g.ax_heatmap.tick_params(axis='x', rotation=90)
g.ax_heatmap.tick_params(axis='y', rotation=0)
# labels = g.ax_heatmap.get_xticklabels()
# g.ax_heatmap.set_xticklabels(labels, rotation=90)
# g.ax_heatmap.set_yticklabels(labels, rotation=0)
# bottom, top = g.ax_heatmap.get_ylim()
# g.ax_heatmap.set_ylim(bottom + 0.5, top - 0.5)

g.fig.savefig(r'similarity' + '.svg', format='svg', dpi=600, bbox_inches="tight")

相关问题 更多 >