一周与一天的 seaborn 热图 python

seaborn heat map for week vs day python

我需要生成一个热图,其中我必须将天数排列为列,将 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

我猜你指的是星期几,否则这将是一个非常奇怪的热图。您可以尝试类似下面的操作,基本上是在您的 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'])