python - Plotly:如何在绘图线图中的特定点添加标记(python / pandas)
问题描述
我有一个 df(如下),并想编写一个函数,该函数将返回一个plotly
折线图,其中包含数据集中指定点的数据标签(该图跟踪促销的成功,所以我想标记促销的开始和结束时间 -但这与数据集本身的开始和结束不同)。
index date x_sales y_sales
0 2019-10-24 0 27
1 2019-10-25 0 30
2 2019-10-26 0 34
3 2019-10-27 0 36
4 2019-10-28 0 29
plotly
文档不清楚如何添加注释,我能找到的唯一相关 StackOverflow 问题是关于R。
理想情况下,我想要一个像这里这样的图表:
但在其中一条线上有一个小标签 forstart date
和一个 for 。end date
我当前的代码是最基本的:
fig = px.line(df_g, x="date", y=df_g.columns)
谢谢你的帮助。
解决方案
customAnnotations()
下面代码片段中的函数将为add_annotation()
您要注释的每个特定点生成此图形:
正如您所指定的,这会生成一个图,其中注释了您指定时期的开始和结束。让我知道这对您有何影响,我们可以根据您的特定需求进行调整。
# 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
df = pd.DataFrame({'date': {3: '2020-08-03',
4: '2020-08-04',
5: '2020-08-05',
6: '2020-08-06',
7: '2020-08-07'},
'title_sales': {3: 2, 4: 4, 5: 3, 6: 6, 7: 2},
'regression_sales': {3: 4, 4: 6, 5: 5, 6: 6, 7: 4},
'causal_sales': {3: 3, 4: 5, 5: 4, 6: 5, 7: 3}})
df.set_index('date', inplace = True)
def customAnnotations(df, xStart, xEnd, yVal):
# xStart = '2020-08-04'
# xEnd = '2020-08-06'
# xVal='date'
# yVal='regression_sales'
fig = go.Figure(data=go.Scatter(x=df.index, y=df[yVal].values, marker_color='black'))
per_start = df[df.index==xStart]
per_end = df[df.index==xEnd]
fig.add_annotation(dict(font=dict(color='rgba(0,0,200,0.8)',size=12),
x=per_start.index[0],
#x = xStart
y=per_start[yVal].iloc[0],
showarrow=False,
text='Period start = ' + per_start.index[0] + ' ',
textangle=0,
xanchor='right',
xref="x",
yref="y"))
fig.add_annotation(dict(font=dict(color='rgba(0,0,200,0.8)',size=12),
x=per_end.index[0],
#x = xStart
y=per_end[yVal].iloc[0],
showarrow=False,
text='Period end = ' + per_end.index[0] + ' ',
#ax = -10,
textangle=0,
xanchor='right',
xref="x",
yref="y"))
fig.show()
customAnnotations(df=df, xStart = '2020-08-04', xEnd = '2020-08-06', yVal='regression_sales')