Group legend in Plotly with Python

Viewed 1682

I'm discovering Plotly on Python and I'm trying to plot "grouped" subplots.

Here is an example of code:

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

fig = make_subplots(rows=1, cols=2, start_cell="bottom-left")

x = [0,1,2,3,4,5,6,7,8,9]

y1 = [10,9,8,7,6,5,4,3,2,1]
y2 = [1,2,3,4,5,6,7,8,9,10]

z1 = [1,1,2,2,3,3,4,4,5,5]
z2 = [6,6,2,2,3,3,1,1,0,0]

fig.add_trace(go.Scatter(x=x, y=y1), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=y2), row=1, col=2)
fig.add_trace(go.Scatter(x=x, y=z1), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=z2), row=1, col=2)

fig.show()

which gives this result: enter image description here

But what I want to do is to "group" the y plots and z plots in the same legend: so in the figure, the blue line and the red line should appear on the same color and correspond to one entry on the legend (and idem for trace 2 and trace 3).

I found some "hand-crafted" solution setting manually the color of the graph, and displaying the legend once over two, but this is not optimal...

Here is an example of what the figure should look like :

result The legend entry "trace 1" would correspond to both y1 and y2, and "trace 2" to z1and z2. So when I ckick on the legend, both lines are hidden.

I don't know if this is quite clear, but here is another topic with the same question.

Thanks!

1 Answers

Specify for each graph the legend you want to group. You can also use lines to set the same color for each group.

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

fig = make_subplots(rows=1, cols=2, start_cell="bottom-left")

x = [0,1,2,3,4,5,6,7,8,9]

y1 = [10,9,8,7,6,5,4,3,2,1]
y2 = [1,2,3,4,5,6,7,8,9,10]

z1 = [1,1,2,2,3,3,4,4,5,5]
z2 = [6,6,2,2,3,3,1,1,0,0]

fig.add_trace(go.Scatter(x=x, y=y1, mode='markers+lines', line=dict(color='Crimson'), legendgroup='group'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=y2, mode='markers+lines', line=dict(color='Blue'), legendgroup='group2'), row=1, col=2)
fig.add_trace(go.Scatter(x=x, y=z1, mode='markers+lines', line=dict(color='Crimson'), legendgroup='group'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=z2, mode='markers+lines', line=dict(color='Blue'), legendgroup='group2'), row=1, col=2)

fig.show()

enter image description here

Related