sns.heatmap绘制热图时y轴无法重写,如何删除多余索引仅显示Hour值?
解决方案
问题根源
你生成的heatmap_df是Hour、Profile_Name组成的双层MultiIndex,按Profile筛选后的子数据集仍然保留双层索引结构,sns.heatmap默认会将多层索引的所有层级内容拼接作为y轴刻度,因此会显示多余的Profile_Name信息。你之前set_yticks不生效的原因是没有接收plt.subplots返回的ax对象,变量未定义自然不会生效。
方案1:预处理索引(推荐)
绘制前删除第二层的Profile_Name索引,仅保留Hour作为单索引,不需要额外修改刻度配置,逻辑最简洁:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 你的原有DataFrame生成代码 df = pd.DataFrame([['Monday', 1, 'Sebastian', 3], ['Monday', 2, 'Sebastian', 6], ['Monday', 3, 'Living room', 10], ['Tuesday', 1,'Sebastian', 6], ['Tuesday', 2,'Sebastian', 3], ['Tuesday', 3,'Sebastian', 8], ['Wednesday', 1,'Sebastian', 6], ['Wednesday', 2,'Sebastian', 3], ['Wednesday', 3,'Sebastian', 9], ['Tuesday', 1,'Living room', 6], ['Monday', 2,'Living room', 10]], columns=['Weekday', 'Hour', 'Profile_Name', 'Counts']) heatmap_df = df.pivot_table(index=('Hour', 'Profile_Name') ,columns='Weekday',values='Counts', aggfunc=lambda x:x).fillna(0) # 修改后的绘图循环 Names = df.Profile_Name.unique() for Profile in Names: fig, ax = plt.subplots(figsize=(15,10)) # 筛选后删除第二层Profile_Name索引,仅保留Hour plot_data = heatmap_df[heatmap_df.index.get_level_values('Profile_Name').isin([Profile])].droplevel('Profile_Name') sns.heatmap(plot_data, annot= True, fmt='g', cmap="Blues", ax=ax) plt.title(Profile, fontsize = 20) plt.xlabel('Weekday', fontsize = 15) plt.ylabel('Time', fontsize = 15) plt.show()
方案2:直接覆盖y轴刻度
如果不想修改源数据,也可以在绘制完成后直接替换y轴的刻度标签:
Names = df.Profile_Name.unique() for Profile in Names: fig, ax = plt.subplots(figsize=(15,10)) plot_data = heatmap_df[heatmap_df.index.get_level_values('Profile_Name').isin([Profile])] sns.heatmap(plot_data, annot= True, fmt='g', cmap="Blues", ax=ax) # 直接替换为对应Hour值,也可以写为ax.set_yticklabels(range(24), rotation=0)强制设置为0-23 ax.set_yticklabels(plot_data.index.get_level_values('Hour'), rotation=0) plt.title(Profile, fontsize = 20) plt.xlabel('Weekday', fontsize = 15) plt.ylabel('Time', fontsize = 15) plt.show()
内容的提问来源于stack exchange,提问作者Sebastian ten Berge
相关产品推荐
相关产品推荐

