多个seaborn热图图将另存为图片

时间:2019-01-28 12:43:08

标签: python matplotlib seaborn

我正在尝试在同一行上彼此相邻放置两个热图。但是我从代码中得到的结果是空白的白色图片。

import matplotlib.pyplot as plt
import seaborn as sns

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")

plt.subplot(2, 1, 1)
plt.figure(figsize=(flights.shape[1], (flights.shape[0] + 2) // 2))
ax = sns.heatmap(flights, annot=True, fmt="d")

plt.subplot(2, 2, 1)
plt.figure(figsize=(1, (flights.shape[0] + 2) // 2))
ax = sns.heatmap(flights.sum(axis=1).to_frame(), annot=True, fmt="d")

fig = ax.get_figure()
fig.savefig("myplot.png",)

我要实现的结果是此图的结果:

plt.figure(figsize=(flights.shape[1], (flights.shape[0] + 2) // 2))
ax = sns.heatmap(flights, annot=True, fmt="d")

和这个:

plt.figure(figsize=(1, (flights.shape[0] + 2) // 2))
ax = sns.heatmap(flights.sum(axis=1).to_frame(), annot=True, fmt="d")

彼此相邻并保存为图片。有什么想法我做错了吗?

1 个答案:

答案 0 :(得分:0)

我有一个解决方案:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import gridspec
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")


fig, (ax1, ax2) = plt.subplots(ncols=2,  gridspec_kw={'width_ratios':[flights.shape[1], 1]}, sharey=True, figsize=(flights.shape[1], (flights.shape[0] + 2) // 2))


sns.heatmap(flights, annot=True, fmt="d", ax=ax1)
sns.heatmap(flights.sum(axis=1).to_frame(), annot=True, fmt="d", ax=ax2)

fig.savefig("myplot.png")