1

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

Example

import numpy as np
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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
mf17
  • 91
  • 6
  • The legend can be called itself and accepts I believe a dictionary of items. I would start wit the modified answer https://stackoverflow.com/a/65654470/13627227 here... I believe it is the last few lines in a variable called c, that is then passed into plt.legend() – thejahcoop Jan 11 '23 at 19:45
  • Does it matter for you if it's under "A" and "B" - or can it be right above the dotted line? – CodeCop Jan 11 '23 at 19:53
  • @thejahcoop, that looks like matplotlib. not plotly? – BigBen Jan 11 '23 at 20:12

1 Answers1

1

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

CodeCop
  • 1
  • 2
  • 15
  • 37