matplotlib和seaborn heatmap在Jupyter中呈现不同的savefig(标签截止)

问题描述 投票:2回答:1

使用Jupyter 4.4.0和Python 3.6.5(Anaconda),我按如下方式生成热图:

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

# generate a 9x4 matrix of random values and long labels
x,y = 9,4
plt.figure(figsize=(x,y))
scores = np.random.random((y, x))
cols = ['looooooooooong_label_x_%d' % i for i in range(x)]
rows = ['looooooooooong_label_y_%d' % i for i in reversed(range(y))]

# generate a heatmap using seaborn with rotated labels
ax = sns.heatmap(pd.DataFrame(scores, columns=cols, index=rows), annot=True, square=True, cbar=False,  cmap='YlGnBu', xticklabels=True, yticklabels=True)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=8)
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, fontsize=8, rotation_mode='anchor', ha='right')

在笔记本中,Jupyter会自动呈现此图像,如下所示:

Jupyter-rendered seaborn/matplotlib heatmap

这看起来完全符合我的要求。但是,当我采取下一步并将绘图保存到文件时:

ax.figure.savefig('hmx.png')

此文件显示为:

seaborn/matplotlib heatmap saved to PNG directly

差异似乎是:

  • 保存的图像似乎向下和向左移动,切断标签;
  • Jupyter渲染的PNG具有透明背景,而保存的图像则没有(它具有白色背景)。

我想知道如何将Jupyter生成的图像保存到文件中,或者更好的是,当我尝试自己保存PNG时,我做错了什么。

python matplotlib jupyter-notebook heatmap seaborn
1个回答
2
投票

固定!

ax.figure.savefig('hmx.png', transparent=True, bbox_inches='tight')

输出现在与Jupyter生成的内容相匹配:透明,正确对齐,没有任何标签被截断:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.