Plotly Express how to show legend?

Question:

I have code below as, but I cant seem to show legend even by trying a few things manually by showing legend parameter, is there anyway to show legend? Thanks!

subfig = make_subplots(specs=[[{"secondary_y": True}]])

# create two independent figures with px.line each containing data from multiple columns
fig = px.line(dfa, y="revenue", template=template_style,markers=True)
fig2 = px.line(dfa, y="pdt_chg", template=template_style,markers=True)

fig2.update_traces(yaxis="y2")

subfig.add_traces(fig.data + fig2.data)
subfig.layout.title="Sales"
subfig.layout.xaxis.title="Year"
subfig.layout.yaxis.title="$"
subfig.layout.yaxis2.title="%"
subfig.update_layout(
    xaxis = dict(
        tickmode = 'linear',
        tick0 = 0,
        dtick = 0),title_x= 0.47,template=template_style)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()
Asked By: Chris90

||

Answers:

When px.line is prompted to produce figure with a single line, the default behavior is to drop the legend. This is presumably intended to reduce redundant informatin since it’s easy to include the data description in the main title and/or the axis title. In order to override this, just include:

fig.for_each_trace(lambda t: t.update(name = <a name>))
fig.update_traces(showlegend = True)

In your case, you’ll have to do so for both your initial figures before they are joined in subfig. Here’s and exampe with the gapminder dataset:

Plot:

enter image description here

Complete code:

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

subfig = make_subplots(specs=[[{"secondary_y": True}]])

df1 = px.data.gapminder().query("country=='Canada'")
fig1 = px.line(df1, x="year", y="lifeExp", title='Life expectancy in Canada')
fig1.for_each_trace(lambda t: t.update(name = 'Canada'))
fig1.update_traces(showlegend = True)


df2 = px.data.gapminder().query("country=='Germany'")
fig2 = px.line(df2, x="year", y="lifeExp", title='Life expectancy in Germany')
fig2.for_each_trace(lambda t: t.update(name = 'Germany'))
fig2.update_traces(showlegend = True)


subfig.add_traces(fig1.data + fig2.data)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))

subfig.show()
Answered By: vestland