每周vs天python的seaborn热图 [英] seaborn heat map for week vs day python

查看:60
本文介绍了每周vs天python的seaborn热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个热图,在这里我必须将天安排为列,将week_num安排为行,绿色安排为正日,红色安排为负日.它应该每天和每周都有休息.

I need to generate a heat map Where I have to arrange days as columns and week_num as rows and Green for a positive day and red for the negative day. It should have break for each day and each week.

我尝试使用seaborn库,但无法成功绘制.有人可以帮我吗?

I have tried using seaborn library but couldn't succeed in plotting this. Can anyone help me with this?

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并在图例中相应地标记它们:

I am guessing you refer to the day of the week, otherwise it will be a really weird heatmap. You can try something like below, basically in something like your data.frame, get the day of week as another column, then pivot this into a wide format and plot. sns.heatmap does not take in categorical values so you need to replace this with 0,1 and label them accordingly in the legend:

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'])

这篇关于每周vs天python的seaborn热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆