python - matplotlib 和 seaborn 热图在 Jupyter 中与 savefig 的渲染方式不同(标签被切断)

标签 python matplotlib jupyter-notebook heatmap seaborn

使用 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 时我做错了什么。

最佳答案

已修复!

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

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

enter image description here

关于python - matplotlib 和 seaborn 热图在 Jupyter 中与 savefig 的渲染方式不同(标签被切断),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51568083/

相关文章:

python - SciTe 编辑器下载并安装?

python - 以清晰的方式在 1 个轴上显示 3 个直方图 - matplotlib

python - 如何将 Python 程序(包括库)发送给 friend ?

python - 使用字典绘制条形图并使用另一个字典为每个条形指定指定的颜色

Python Matplotlib slider 小部件未更新

python - Jupyter Notebook 中的全局行号

python - 在 Graphql 查询中收到不兼容的实例

python - 将 matplotlib 偏移表示法从科学更改为简单

python-3.x - 从 jupyter 实验室复制 matlibplot 绘图图像

python - 仅在 azure ml studio 中使用 python 笔记本创建 azure ml 实验