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()
这篇关于如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?
基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01