【问题标题】:seaborn heat map for week vs day python一周与一天 python 的 seaborn 热图
【发布时间】:2021-06-12 04:38:21
【问题描述】:

我需要生成一个热图,我必须将天安排为列,将 week_num 安排为行,绿色代表积极的一天,红色代表消极的一天。 它应该每天和每周都有休息时间。

我曾尝试使用 seaborn 库,但未能成功绘制此图。谁能帮我解决这个问题?

week_num    day    color_code
    1   2020-05-01  red
    1   2020-05-02  green
    2   2020-05-05  red
    2   2020-05-06  red
    3   2020-05-13  green
    3   2020-05-14  green
    3   2020-05-15  red

【问题讨论】:

    标签: python python-3.x seaborn heatmap


    【解决方案1】:

    我猜你指的是星期几,否则这将是一个非常奇怪的热图。您可以尝试类似下面的内容,基本上在您的 data.frame 中,将星期几作为另一列,然后将其转换为宽格式并绘制。 sns.heatmap 不接受分类值,因此您需要将其替换为 0,1 并在图例中相应地标记它们:

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    dates = pd.date_range(start='1/1/2018', periods=60, freq='1D')
    color_code = np.random.choice(['green','red'],60)
    df = pd.DataFrame({'dates':dates ,'color_code':color_code})
    df['week_num'] = df['dates'].dt.strftime("%W")
    df['day_num'] = df['dates'].dt.weekday
    
    fig, ax = plt.subplots(1, 1, figsize = (5, 3))
    
    df_wide = df.pivot_table(index='week_num',columns='day_num',values='color_code',
    aggfunc=lambda x:x)
    sns.heatmap(df_wide.replace({'green':0,'red':1}),cmap=["#2ecc71","#e74c3c"],
                linewidths=1.0,ax=ax)
    colorbar = ax.collections[0].colorbar
    colorbar.set_ticks([0.25,0.75])
    colorbar.set_ticklabels(['green','red'])
    

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2020-09-01
      • 2021-11-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      相关资源
      最近更新 更多