You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Seaborn绘制的热力图X轴标签置于顶部?

Seaborn热力图X轴标签置顶或双端显示解决方案

问题背景

使用Seaborn + Matplotlib生成的热力图已满足分析需求,但需要将X轴标签从默认底部调整至顶部,或同时在上下两侧显示。尝试过Plotly Express实现标签置顶,但无法还原Seaborn的热力图样式,需基于原Seaborn代码修改。

示例数据

NP                  NP1       NP2       NP3       NP4       NP5
identifier                                                     
A1BG~P04217   -0.094045  0.012229  0.102279  1.319618  0.002383
A2M~P01023    -0.805089 -0.477339 -0.351341  0.089735 -0.473815
AARS1~P49588   0.081827 -0.099849 -0.287426  0.101588  0.136366
ABCB6~Q9NP58   0.109911  0.458039 -0.039325 -0.484872  1.905586
ABCC1~I3L4X2  -0.560155  0.580285  0.012868  0.291303 -0.407900
ABCC4~O15439   0.055264  0.138630 -0.204665  0.191241  0.304999
ABCE1~P61221  -0.510108 -0.059724 -0.233365  0.078956 -0.651327
ABCF1~Q8NE71  -0.348526 -0.135414 -0.390021 -0.190644 -0.276303
ABHD10~Q9NUJ1  0.237959 -2.060834  0.325901 -0.778036 -4.046345
ABHD11~Q8NFV4  0.294587  1.193258 -0.797294 -0.148064 -1.153391

原生成代码

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

# 读取数据并转为DataFrame
df_example = pd.read_csv("your_data_path.csv", index_col="identifier")

fig, ax = plt.subplots(figsize=(10,30))
ax = sns.heatmap(df_example, annot=True, xticklabels=True)
plt.show()

解决方案

方案1:仅将X轴标签移至顶部

直接通过Matplotlib的轴对象调整,无需修改Seaborn核心调用:

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

df_example = pd.read_csv("your_data_path.csv", index_col="identifier")

fig, ax = plt.subplots(figsize=(10,30))
ax = sns.heatmap(df_example, annot=True, xticklabels=True)

# 将X轴刻度移至顶部
ax.xaxis.tick_top()
# 将X轴标题同步移至顶部
ax.set_xlabel(ax.get_xlabel(), loc='top')
# 可选:调整标签水平对齐方式,让显示更规整
ax.set_xticklabels(ax.get_xticklabels(), ha='center')

plt.show()

方案2:同时显示上下两侧的X轴标签

通过创建双轴(twiny())实现双端标签,确保两个轴的刻度与热力图范围完全匹配:

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

df_example = pd.read_csv("your_data_path.csv", index_col="identifier")

fig, ax = plt.subplots(figsize=(10,30))
ax = sns.heatmap(df_example, annot=True, xticklabels=True)

# 创建顶部的双轴
ax_top = ax.twiny()
# 同步顶部轴的刻度位置和标签与原轴一致
ax_top.set_xticks(ax.get_xticks())
ax_top.set_xticklabels(ax.get_xticklabels())
# 匹配顶部轴的范围与热力图,避免错位
ax_top.set_xlim(ax.get_xlim())

# 若需要隐藏底部标签,取消下方注释
# ax.set_xticklabels([])

plt.show()

内容的提问来源于stack exchange,提问作者Bob McBobson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:30:57