[Python] Plotly: How to set up multiple subplots with grouped legends?

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    for each subplot I have 3 seperate line:2017 ,2018 and 2019 with 3 times "go.Scatter", each subplot represents one country (25 countries) with always these 3 years. I can use the subplot sample code but then all the 75 legends (25 X 3) will be all together with different colors and it's messy.

    I don't need different colors amont different subplot, I can just have 3 different colors and 3 legends for the 3 years on all subplots, would be ideal if I click on for example 2017 that all the 2017 curve/line dissappear across the 25 subplots.

    Anyone can share a sample code? it can be 2 instead of 25 for illustration purpose. I fail to find this sample code on Plotly website.

    Edit: this is a sample code:

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

    fig = make_subplots(rows=3, cols=1)

    fig.add_trace(go.Scatter(
    x=[3, 4, 5],
    y=[1000, 1100, 1200],name="2017",
    ), row=1, col=1)

    fig.add_trace(go.Scatter(
    x=[2, 3, 4],
    y=[1200, 1100, 1000],name="2018",
    ), row=1, col=1)


    fig.append_trace(go.Scatter(
    x=[2, 3, 4],
    y=[100, 110, 120],name="2017",
    ), row=2, col=1)

    fig.append_trace(go.Scatter(
    x=[2, 3, 4],
    y=[120, 110, 100],name="2018",
    ), row=2, col=1)

    fig.append_trace(go.Scatter(
    x=[0, 1, 2],
    y=[10, 11, 12],name="2017",
    ), row=3, col=1)

    fig.append_trace(go.Scatter(
    x=[0, 1, 2],
    y=[12, 11, 10],name="2018",
    ), row=3, col=1)

    fig.update_layout(height=600, width=600, title_text="Stacked Subplots")
    offline.plot(fig,filename="subplots.html")


    I wish to have only 2 legends: 2017 and 2018, instead of 6 legends, easier if all the 2017 has same color along the 3 subplots

    Continue reading...

Compartilhe esta Página