在时间序列数据中以阴影突出显示类别列

问题描述

在这里我有一个时间序列数据,我正尝试使用复制的plotly进行绘图。我有一个分类fill_cat,它们分别是二进制1或0。如果存在1,则应绘制垂直线或阴影以标识是否存在事件1。

Glimpse of Data set

Expected visualisation

 import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import datetime

pd.set_option('display.max_rows',None)

# data sample
nperiods = 200
np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10,12,size=(nperiods,4)),columns=list('ABCD'))
datelist = pd.date_range(datetime.datetime(2020,1,1).strftime('%Y-%m-%d'),periods=nperiods).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum().reset_index()
df['fill_cat'] = [0,0] 
df.head()

fig = px.line(df,x='dates',y=df.columns[1:])
fig.update_xaxes(showgrid=True,gridwidth=1,gridcolor='rgba(0,255,0.1)')
fig.update_yaxes(showgrid=True,0.1)')
fig.show()

解决方法

答案是使用官方参考文献准备的。 add_vrect()可以在图形上添加矩形。如果它变成一个带有手动开始和结束的间隔,则可以对其进行着色,但是我采用的方法是对“ fii_cat”提取的数据帧使用循环处理。 (每天都有)我认为这是效果。填充颜​​色未启用。

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import datetime

pd.set_option('display.max_rows',None)

# data sample
nperiods = 200
np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10,12,size=(nperiods,4)),columns=list('ABCD'))
datelist = pd.date_range(datetime.datetime(2020,1,1).strftime('%Y-%m-%d'),periods=nperiods).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum().reset_index()
df['fill_cat'] = [0,0] 
df.head()


fig = px.line(df,x='dates',y=df.columns[1:])
fig.update_xaxes(showgrid=True,gridwidth=1,gridcolor='rgba(0,255,0.1)')
fig.update_yaxes(showgrid=True,0.1)')

fill_data = df[df['fill_cat'] == 1]
for idx,row in fill_data.iterrows():
    d = str(row.dates.strftime('%Y-%m-%d'))
    fig.add_vrect(x0=str(row.dates.strftime('%Y-%m-%d')),x1=str(row.dates.strftime('%Y-%m-%d')),fillcolor='yellow',opacity=0.5,line_width=2)

fig.show()

enter image description here