Skip to content

Multiple legends does not work with subplots #4264

Closed
@msimoni18

Description

@msimoni18

@LiamConnors

According to an email I received on June 21st regarding updates to plotly 5.15.0, I should be able to include multiple legends on a figure with subplots. I copy and pasted the example into a JupyterLab Lite notebook and confirmed I was using plotly 5.15.0 by printing plotly.__version__. When I run the code, it does not match the image in the email. Instead of having two legends, only one legend is included and moved to x: 0.4.

Any ideas as to why I cannot reproduce the example provided in the email?

Code from the email:

import plotly.graph_objects as go
from plotly import data
from plotly.subplots import make_subplots

df = data.gapminder()

subplot_1_countries = ["Germany", "France", "United Kingdom"]
subplot_2_countries = ["United States", "Canada"]

fig = make_subplots(
    rows=1,
    cols=2,
    horizontal_spacing=0.2,
    shared_yaxes=True,
)

for country in subplot_1_countries:
    filtered_data = df.loc[(df.country.isin([country]))]
    fig.add_trace(
        go.Scatter(x=filtered_data.year, y=filtered_data.lifeExp, name=country),
        row=1,
        col=1,
    )

for country in subplot_2_countries:
    filtered_data = df.loc[(df.country.isin([country]))]
    fig.add_trace(
        go.Scatter(
            x=filtered_data.year,
            y=filtered_data.lifeExp,
            name=country,
            legend="legend2",
        ),
        row=1,
        col=2,
    )

fig.update_layout(
    title="Life Expectancy Subplots with Multiple Legends",
    plot_bgcolor="#E6F1F6",
    legend={
        "x": 0.4,
    },
)

fig.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions