I have a df (below) and want to write a function that will return a plotly
line graph with data labels at specified points within the dataset (this graph tracks the success of a promotion, so I want to mark when the promo begins and ends - but that is not the same as the start and end of the dataset itself).
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
The plotly
docs are unclear about how to add annotations and the only relevant StackOverflow question I can find is about R.
Ideally, I would like a graph like the one here:
but with a little label for start date
and one for end date
on one of the lines.
My current code is as basic as it gets:
fig = px.line(df_g, x="date", y=df_g.columns)
Thanks for any help.
The function customAnnotations()
in the code snippet below will produce this figure using add_annotation()
for each specific point you'd like to annotate:
As you've specified, this produces a figure where the start and end of your specified period are annotated. Let me know how this works out for you and we can adjust it to your specific needs.
# 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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.