import pandas as pd
import numpy as np
import plotly.graph_objects as go
# generate a time series
df = pd.DataFrame({
'date': pd.date_range(start='2021-01-01', periods=18, freq='D'),
'value': 100 * np.cumsum(np.random.normal(loc=0.01, scale=0.005, size=18))
})
# define the y-axis limits
ymin, ymax = df['value'].min() - 5, df['value'].max() + 5
# create an auxiliary time series for highlighting the weekends, equal
# to "ymax" on Saturday and Sunday, and to "ymin" on the other days
df['weekend'] = np.where(df['date'].dt.day_name().isin(['Saturday', 'Sunday']), ymax, ymin)
# define the figure layout
layout = dict(
plot_bgcolor='white',
paper_bgcolor='white',
margin=dict(t=5, b=5, l=5, r=5, pad=0),
yaxis=dict(
range=[ymin, ymax], # fix the y-axis limits
tickfont=dict(size=6),
linecolor='#000000',
color='#000000',
showgrid=False,
mirror=True
),
xaxis=dict(
type='date',
tickformat='%d-%b-%Y (%a)',
tickfont=dict(size=6),
nticks=20,
linecolor='#000000',
color='#000000',
ticks='outside',
mirror=True
),
)
# add the figure traces
data = []
# plot the weekends as a filled area chart
data.append(
go.Scatter(
x=df['date'],
y=df['weekend'],
fill='tonext',
fillcolor='#d9d9d9',
mode='lines',
line=dict(width=0, shape='hvh'),
showlegend=False,
hoverinfo=None,
)
)
# plot the time series as a line chart
data.append(
go.Scatter(
x=df['date'],
y=df['value'],
mode='lines+markers',
marker=dict(size=4, color='#cc503e'),
line=dict(width=1, color='#cc503e'),
showlegend=False,
)
)
# create the figure
fig = go.Figure(data=data, layout=layout)
# save the figure
fig.write_image('figure.png', scale=2, width=500, height=300)
我会考虑使用^ {CD1>},并将一个^ {< CD2>}附加到第二个y轴上,作为背景颜色而不是形状来指示周末。
绘图:
对于我的系统上下面代码段中的
nperiods = 2000
,%%timeit
返回:我最初建议使用
fig.add_shape()
的方法要慢得多:完整代码:
您可以使用填充区域图表一次突出显示所有周末,而无需使用循环,也无需创建多个形状,有关示例,请参见下面的代码
相关问题 更多 >
编程相关推荐