如何在特定工作日(周六和周日)使用垂直颜色条突出显示绘图图? [英] How to highlight a plotline chart with vertical color bar for specific weekdays (saturday and sunday)?

查看:79
本文介绍了如何在特定工作日(周六和周日)使用垂直颜色条突出显示绘图图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绘制了航班的日线图,我想强调所有周六和周日.我正在尝试使用axvspan来做,但是我在努力使用它?关于如何编码的任何建议?

 (flights.loc [flights ['date'].dt.month.between(1,2),'date'].dt.to_period('D').value_counts().sort_index().plot(kind ="line",figsize =(12,6)))

提前感谢您提供的任何帮助

解决方案

使用 pandas 时间戳类型的日期列,可以直接使用

包含示例数据的完整代码

 #个导入将numpy导入为np将熊猫作为pd导入随地导入plotly.graph_objects导入plotly.express为px导入日期时间pd.set_option('display.max_rows',无)# 数据样本cols = ['信号']n周期 = 20np.random.seed(12)df = pd.DataFrame(np.random.randint(-2,2,size =(nperiods,len(cols))),列=列)datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),periods=nperiods).tolist()df['date'] = 日期列表df = df.set_index(['date'])df.index = pd.to_datetime(df.index)df.iloc [0] = 0df = df.cumsum().reset_index()df ['signal'] = df ['signal'] + 100#绘图设置无花果= px.line(df,x ='date',y = df.columns [1:])fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,255,0.1)')fig.update_yaxes(showgrid = True,gridwidth = 1,gridcolor ='rgba(0,0,255,0.1)')对于索引,在df.iterrows()中的行:如果row ['date'].weekday()== 5:#or row ['date'].weekday()== 6:fig.add_shape(type="rect",外部参照 =x",yref=纸",x0 = row ['date'],y0 = 0,# x1=row['date'],x1=row['date'] + pd.DateOffset(1),y1=1,line=dict(color=rgba(0,0,0,0)",width=3,),填充颜​​色=rgba(0,0,0,0.1)",层='下面')图.show()

i plotted a daily line plot for flights and i would like to highlight all the saturdays and sundays. I'm trying to do it with axvspan but i'm struggling with the use of it? Any suggestions on how can this be coded?

(flights.loc[flights['date'].dt.month.between(1, 2), 'date']
         .dt.to_period('D')
         .value_counts()
         .sort_index()
         .plot(kind="line",figsize=(12,6))
 )

Thx in advance for any help provided

解决方案

Using a date column of type pandas timestamp, you can get the weekday of a date directly using pandas.Timestamp.weekday. Then you can use df.iterrows() to check whether or not each date is a saturday or sunday and include a shape in the figure like this:

for index, row in df.iterrows():
    if row['date'].weekday() == 5 or row['date'].weekday() == 6:
        fig.add_shape(...)

With a setup like this, you would get a line indicating whether or not each date is a saturday or sunday. But given that you're dealing with a continuous time series, it would probably make sense to illustrate these periods as an area for the whole period instead of highlighting each individual day. So just identify each saturday and set the whole period to each saturday plus pd.DateOffset(1) to get this:

Complete code with sample data

# imports
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
cols = ['signal']
nperiods = 20
np.random.seed(12)
df = pd.DataFrame(np.random.randint(-2, 2, size=(nperiods, len(cols))),
                  columns=cols)
datelist = pd.date_range(datetime.datetime(2020, 1, 1).strftime('%Y-%m-%d'),periods=nperiods).tolist()
df['date'] = datelist 
df = df.set_index(['date'])
df.index = pd.to_datetime(df.index)
df.iloc[0] = 0
df = df.cumsum().reset_index()
df['signal'] = df['signal'] + 100

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

for index, row in df.iterrows():
    if row['date'].weekday() == 5: #or row['date'].weekday() == 6:
        fig.add_shape(type="rect",
                        xref="x",
                        yref="paper",
                        x0=row['date'],
                        y0=0,
#                         x1=row['date'],
                        x1=row['date'] + pd.DateOffset(1),
                        y1=1,
                        line=dict(color="rgba(0,0,0,0)",width=3,),
                        fillcolor="rgba(0,0,0,0.1)",
                        layer='below') 
fig.show()

这篇关于如何在特定工作日(周六和周日)使用垂直颜色条突出显示绘图图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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