Legend position and wrap into 2 rows


Plotted the above chart, however the Chart Legend and the Title will be overlapped when displaying on smaller monitor with lower resolution.

How can we wrap the legend into 2 rows (i.e. Bivent, Combined Sys/Diasit, Systolic and Diastoic on the first row, while the 2nd row gets the “Right, Left and Unknown”) by Python code ? and how can we force the position of legend to be after the title ?

TIA.

Hi @aiya6502 ,

If you want to make multiple rows for horizontal legend, you can by splitting the legends into legend and legend2 .

for example :
legend : Bivent, Combined Sys/Diasit, Systolic and Diastoic
legend2: Right, Left and Unknown

By setting the yanchor="bottom" and playing with y values, you can display them as multiple rows.

Here is the example code:
legend : Germany, France, UK
legend2: Americas , Europe

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=dict(
                orientation="h",
                yanchor="bottom",
                y=1.08,
                xanchor="right",
                x=1),
        legend2=dict(orientation="h",
                yanchor="bottom",
                y=1.02,
                xanchor="right",
                x=1),
    ),
)

fig.show()

Hope this help.