Home > Net >  How to add a hline or vline to a plotly express legend in Python
How to add a hline or vline to a plotly express legend in Python

Time:01-12

I'm trying to add my hline to the legend and label it as 'mean'. Is this possible and if so how.

Example

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'day':np.repeat(np.arange(1, 11,1), 2),
                   'value':np.repeat([1,2,3,4,5],4),
                   'var':list(['A','B'])*10})

fig = px.bar(df,
             x='day',
             y='value',
             color='var')

fig.add_hline(y=df['value'].mean(), line_dash="dot")

fig.show()

Expected outcome enter image description here

CodePudding user response:

You can use the annotation_text parameter in fig.add_hline:

fig.add_hline(y=df['value'].mean(), line_dash="dot", annotation_text="mean")

That would add a text right above the dotted line:

enter image description here

However, the text will not be right under the "Var" section.
In order to do this, you will need to change it from add_hline to add_trace as it is not subject to the legend:

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

df = pd.DataFrame({'day': np.repeat(np.arange(1, 11, 1), 2),
                   'value': np.repeat([1, 2, 3, 4, 5], 4),
                   'var': list(['A', 'B']) * 10})

fig = px.bar(df,
             x='day',
             y='value',
             color='var')

fig.add_trace(go.Scatter(
    x=df['day'],
    y=[df['value'].mean()] * len(df['day']),
    mode='lines',
    name='mean',
    line=dict(dash='dot', width=2, color='black'),
))

fig.show()

Which results in this figure:

enter image description here

  • Related