海上热图的次要X轴

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

我有以下的DataFrame(称为 hehe):

    11  22  33  44  55  66  77
s1  -3  5   7   8   -9  4   7
s2  4   3   8   1   4   4   -12
s3  1   -2  1   -4  8   8   -8
s4  -6  4   -4  9   -4  2   -6

然后是下面的代码:

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(6,4), gridspec_kw={'width_ratios':(1,15)})
sns.heatmap(hehe, ax=ax2, cbar=False, cmap="coolwarm", linewidth=1, vmin=-25, vmax=25)
ax2.set_aspect("equal")
ax2.set_title("A", fontsize=20, pad=30)

plt.colorbar(plt.cm.ScalarMappable(cmap="coolwarm", norm=mpl.colors.Normalize(vmin=-25, vmax=25)), cax=ax1)
ax1.yaxis.set_ticks_position('left')

生成一个图。enter image description here

我想在热图的顶部添加一个额外的X轴,这将帮助我用星号标记列(为了统计意义)。比方说,这将是。new_annotation = ["","","","","*","*",""] 我不知道如何实现这个功能... 我一直在玩复制轴的游戏,用 twiny() 但由于某些原因,它对我不起作用:整个热图出界了。

python matplotlib data-visualization seaborn
1个回答
1
投票

你可以做这样的事情。

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

# hehe = pd.read_clipboard()
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(6,4), gridspec_kw={'width_ratios':(1,15)})
sns.heatmap(hehe, ax=ax2, cbar=False, cmap="coolwarm", linewidth=1, vmin=-25, vmax=25)
# ax2.set_aspect("equal")
ax2.set_title("A", fontsize=20, pad=40)

ax3 = ax2.twiny()
# ax3.set_aspect("equal")
ax3.set_xlim([0,ax2.get_xlim()[1]])
ax3.set_xticks(ax2.get_xticks())
ax3.set_xticklabels(["","","","","*","*",""], fontsize=16)
ax3.tick_params(top=False)
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)

plt.colorbar(plt.cm.ScalarMappable(cmap="coolwarm", norm=plt.Normalize(vmin=-25, vmax=25)), cax=ax1)
ax1.yaxis.set_ticks_position('left')

# plt.tight_layout()
# plt.show()

产生这个图像。

enter image description here

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