Adding a bar chart to an existing line chart makes the line chart legend disappear

So I have this code:

def LineAndBarChart(df=None):
    fig = px.line(
        df,
        x="month",
        y="sales",
    )
    fig.add_bar(x=df["month"], y=df["bottles_sold"])
    fig.update_layout(
        plot_bgcolor="rgba(0,0,0,0)",
        paper_bgcolor="rgba(0,0,0,0)",
        legend=dict(
            orientation="h",
            yanchor="middle",
            y=1.1,
            xanchor="center",
            x=0.5,
            title={'text': None}
        ),
        margin={"t": 30, "b": 0, "r": 20, "l": 0, "pad": 0},
    )
    fig.update_yaxes(title_text='')
    fig.update_xaxes(title_text='')
    return fig

Which makes this graph:


I am adding another trace to the figure and it messed up the legend how can I fix this?
Thanks for taking your time to help!

Hi,

I don’t think express sets the legend in the first trace in this situation (where a single trace is generated). A quick fix is to
wrap the y parameter in a list:

px.line(
        df,
        x="month",
        y=["sales"],
)

Another alternative would be to set showlegend explicitly for the first trace with fig.data[0].showlegend = True, but I am not sure if px will set a name for the trace if it is hidden from the legend.

1 Like