How do I add a second legend to my plotly graph?

Hello, I am trying to figure out how to make a separate legend to show which symbols go to what superconductor type in Plotly express.


The legend on the right contains both the superconductor type, and the reference from which they originate. Is there a way to break those two up into separate legends?

For example I would like to have a legend below the title that says ( square= Ta, circle=Nb…) to better separate the data overlap in the current legend. and a legend on the right that depicts the information that it does currently.

Hi @dylanblevins49 !

Yes you can have more than one legend.

Take a look:

Or alternatively, you can create groups:

Hi, I just tried the code snippet from the example in the latest version of Plotly (5.18), Python 3.12

But only a single legend is appearing:

The code I tried is copy-pasted from the example:

import plotly.graph_objects as go
from plotly import data

df = data.gapminder()

df_germany = df.loc[(df.country.isin(["Germany"]))]
df_france = df.loc[(df.country.isin(["France"]))]
df_uk = df.loc[(df.country.isin(["United Kingdom"]))]


df_averages_europe = (
    df.loc[(df.continent.isin(["Europe"]))].groupby(by="year").mean(numeric_only=True)
)
df_averages_americas = (
    df.loc[(df.continent.isin(["Americas"]))].groupby(by="year").mean(numeric_only=True)
)


fig = go.Figure(
    data=[
        go.Scatter(x=df_germany.year, y=df_germany.gdpPercap, name="Germany"),
        go.Scatter(x=df_france.year, y=df_france.gdpPercap, name="France"),
        go.Scatter(x=df_uk.year, y=df_uk.gdpPercap, name="UK"),
        go.Scatter(
            x=df_averages_europe.index,
            y=df_averages_europe.gdpPercap,
            name="Europe",
            legend="legend2",
        ),
        go.Scatter(
            x=df_averages_americas.index,
            y=df_averages_americas.gdpPercap,
            name="Americas",
            legend="legend2",
        ),
    ],
    layout=dict(
        title="GDP Per Capita",
        legend={
            "title": "By country",
            "xref": "container",
            "yref": "container",
            "y": 0.65,
            "bgcolor": "Orange",
        },
        legend2={
            "title": "By continent",
            "xref": "container",
            "yref": "container",
            "y": 0.85,
            "bgcolor": "Gold",

        },
    ),
)

fig.show()

Best regards,
Juanmi

EDIT: Actually when saving the figure it works (svg, png, html), so it seems to be buggy only in Jupyter notebooks environments

Are you using Jupiter >= 4?

There are some compatibility issues…

I guess you are referring to the jupyter_core module, indeed it’s above 4:

From now on I will try exporting the figures first to rule out these kind of problems

Thanks!

Yeah, i was referring to jupyterlab, but it’s > 4. There are some forum posts about it, this one for example:

1 Like