Using Python 3.8, Plotly 4.13.
Within my scatterplot, I've added multiple vertical lines using add_vline()
method in plotly. However I cannot add it to legend allowing me to turn on/off vertical lines.
How can add vertical lines to the legend?
Here is example of how I've created my plot:
fig = go.Figure()
fig.add_trace(
go.Scatter(name="name added to legend", datas...)
)
for dt in dates:
fig.add_vline(x=dt, line_width=1, etc...)
outputting something like this:
all plots created using go.Scatter
are added to legend however not vertical lines created by fig.add_vline
.
The vertical line is just a decoration of the graph, not a graph object, so it is not included in the legend. So if you want to use the ON/OFF function in the legend, you can add a new one in go.Scatter and use it for the function to select in the legend. I modified the example from the official reference to create the code.
import plotly.express as px
import plotly.graph_objects as go
df = px.data.stocks()
dmax = df[['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT']].values.max()
dmin = df[['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT']].values.min()
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.date, y=df['AAPL'], mode='lines', name='AAPL'))
fig.add_trace(go.Scatter(x=df.date, y=df['GOOG'], mode='lines', name='GOOG'))
fig.add_trace(go.Scatter(x=[df.date[10],df.date[10]],
y=[dmin,dmax],
mode='lines',
line=dict(color='green', width=2, dash='dash'),
name='2018-03-12'))
fig.show()