【问题标题】:Change heatmap's yticks for multi-index dataframe更改多索引数据框的热图 xticks
【发布时间】:2021-06-28 01:35:11
【问题描述】:

下面是从 MultiIndex 数据框生成的 seaborn 热图:

import numpy as np
import pandas as pd
import seaborn as sns

years = range(2016,2019)
months = range(1,6)
df = pd.DataFrame(index=pd.MultiIndex.from_product([years,months]))
df['vals'] = np.random.random(size=len(df))
sns.heatmap(df)

上述热图的 yticks 显示年份和月份。有没有办法将热图的 yticks 更改为仅显示年份,如下所示?

【问题讨论】:

    标签: python pandas numpy matplotlib seaborn


    【解决方案1】:

    使用sns.heatmapyticklabels 参数设置自定义标签

    1. 创建一个空字符串列表,除了所需的索引

      任一:仅在月份为 3 时显示标签

      labels = [year if month == 3 else '' for year, month in df.index]
      

      或:仅在特定行上显示标签(OP 示例中的索引 2、7 和 12)

      labels = [year if row in (2, 7, 12) else ''
                for row, (year, month) in enumerate(df.index)]
      
    2. 然后通过yticklabels设置这些标签

      sns.heatmap(df, yticklabels=labels)
      

    注意事项:

    • month == 3row in (2, 7, 12) 等条件特定于 OP 的示例,需要针对真实数据进行调整。
    • 如果您有datetime 索引(不仅仅是字符串),请参阅this answer for spacing out datetime yticks

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2020-04-01
      • 1970-01-01
      • 2020-06-24
      • 2021-10-11
      • 2020-06-26
      相关资源
      最近更新 更多