Search code examples
python-3.xpandasplotlylegendsubplot

Legend doesn't show up in Plotly Express line subplots


There are several answers for showing the legend if you're using plotly.graph_objs. I'm only using plotly_express though, and can't get the legend to show up when using several subplots.

I have the following code.

import plotly.express as px
from plotly.subplots import make_subplots


subfig = make_subplots(specs=[[{"secondary_y": True}]])
fig1 = px.line(df1, 
               x='col1', 
               y='col2',
)
fig2 = px.line(df2, 
               x='col1', 
               y='col2',
)

# Add a second y-axis
fig2.update_traces(yaxis="y2")

# Combine the two figs into one graph
subfig.add_traces(fig1.data + fig2.data)

I've tried to add the following (as recommended by answers addressing plotly.graph_objs), but without result:

subfig.update_layout(showlegend=True)

px.line() doesn't have a name attribute you can update either.

How do I make the legend show up for plotly express subplots?


Solution

  • I was able to solve it by updating to the following:

    # Add a second y-axis and show legend
    fig2.update_traces(yaxis="y2", showlegend=True)
    fig1.update_traces(showlegend=True)
    
    # Combine the two figs into one graph
    subfig.add_traces(fig1.data + fig2.data)
    
    # Update legend titles
    subfig.data[0].name = "Title line 1"
    subfig.data[1].name = "Title line 2"
    

    You might also be able to use subfig.for_each_trace(...) (haven't tried it though), but I prefer this more direct approach.