Search code examples
pythonplotlylegend

Change layout of legend2 in plotly


How to change layout of legend2 with fig.update_layout()?

import plotly.express as px
import pandas as pd
numbers = pd.DataFrame([[1,2,3,4], [2,3,4,5], [5,7,8,8]])
asdf = px.line(numbers)
asdf = asdf.add_scatter(
    x=[4,3],
    y=[1,2],
    legend="legend2"
)
asdf = asdf.update_layout(
    legend_font=dict(size=20),
    legend2_font=dict(size=20),
)
asdf

Solution

  • The "magic underscore" notation doesn't fully work when updating layout.legend2, because there is no (default for) legend2 in the layout, even it is referenced by one of the scatter traces (unlike with axes, eg. a reference to 'x2' will make plotly defines layout.xaxis2).

    So to make it work you need to define legend2 as a dictionary, under that key you can use underscore shortcuts :

    asdf.update_layout(
        legend_font_size=20,
        legend2=dict(font_size=20, y=0.8)
    )