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

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

问题描述

我为航班绘制了每日线图,我想突出显示所有周六和周日.我正在尝试用 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['信号'] = df['信号'] + 100# 情节设置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)')对于索引,df.iterrows() 中的行:if row['date'].weekday() == 5: #or row['date'].weekday() == 6:fig.add_shape(type="rect",外部参照=x",yref=纸",x0=行['日期'],y0=0,# x1=行['日期'],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天全站免登陆