Search code examples
pythonplotly

How to Insert numerical information at plotly chart legend


I'm trying to added some data at my chart legends but i don't know how. I did search at plotly docs at https://plotly.com/python/legend/ but none of those examples available bring this feature. In the figure below is showed what i want to do. As you can see there is a legend of my chart and i want insert the data corresponded to the name of legend, i.g: UCL - 100, ICL - 50 and so on.

Here is what i have: enter image description here

Here is a real example of what i really aim to: enter image description here

A piece of the code i'm using is below, I can't share the rest:

        fig.add_trace(go.Scatter(
            x=df_mean_control_chart['Samples'],
            y=df_mean_control_chart['UCL'],
            mode='lines',
            name='UCL',
            line=dict(color='black', width=2)))

Description of the variables:

df_mean_control_chart['Samples'] and df_mean_control_chart['UCL'] = it's a column of a data from a dataframe which only contains numerical data.


Solution

  • You can add numerical values to the legend by using f-string to add the numerical value you wish to add to the legend.

    import plotly.express as px
    import plotly.graph_objects as go
    
    df = px.data.stocks()
    goog_max = df['GOOG'].max()
    goog_mean = df['GOOG'].mean()
    goog_min = df['GOOG'].min()
    
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df.index, y=df['GOOG'], name='GOOG'))
    
    fig.add_trace(go.Scatter(mode='lines',
                             x=df.index, 
                             y=[goog_mean]*len(df),
                             name=f'GOOG {round(goog_mean,2)}'))
    fig.add_trace(go.Scatter(mode='lines',
                             x=df.index, 
                             y=[goog_max]*len(df), 
                             name=f'GOOG {round(goog_max,2)}'))
    fig.add_trace(go.Scatter(mode='lines',
                             x=df.index, 
                             y=[goog_min]*len(df), 
                             name=f'GOOG {round(goog_min,2)}'))
    
    fig.show()
    

    enter image description here