How to highlight a plotline chart with vertical color bar for specific weekdays (saturday and sunday)?(如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?)
问题描述
我为航班绘制了每日线图,我想突出显示所有周六和周日.我正在尝试用 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()
这篇关于如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
