1
votes

I have this code:

from datetime import timedelta, datetime
def plot_values(times, values, index_names):
    fig = make_subplots(rows=1, cols=2, start_cell="bottom-left")
    for i in range(len(times)):
        fig.add_trace(go.Scatter(x=times[i], y=values[i], name=index_names[i]),
                      row=1,
                      col=1)
        
        fig.add_trace(go.Scatter(x=list(range(len(times))), y=values[i], name=index_names[i]),
                      row=1,
                      col=2)
    fig = fig.update_traces(visible="legendonly")
    fig.show()

    
values = [[i for i in range(10)],
         [i + 1 for i in range(10)]]
    
times = [[datetime.now() + timedelta(minutes=i) for i in range(10)],
         [datetime.now() + timedelta(minutes=5) + timedelta(minutes=i) for i in range(10)]]

names = ["name " + str(i) for i in range(10)]

plot_values(times, values, names)

enter image description here

This code duplicate the indexes. how can I combine the 2 subplots to have only 2 indexes: name 0 and name 1.

1
you are creating four traces, hence all four are displayed in legend. subplot behaviour is consistent in this respect. I really don't see a way to make it work effectively with a legend that is not consistent with number of tracesRob Raymond

1 Answers

0
votes

If I'm understanding your request correctly, you can get the desired functionality with the correct combinations of the following for each trace: name, legendgroup and showlegend

The first plot shows an example from subplots:

Plot 1: Original setup

enter image description here

And if you use the code snippet below instead, you'll get the following plot:

Plot 2: Legend behaviour changed with name, legendgroup and showlegend

enter image description here

Here, clicking name 1 in the legend will toggle both trace 1 and trace 2

Plot 3: Toggle functionality:

enter image description here

I hope this is what you were looking for. Don't hesitate to let me know if not.

Complete code:

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

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

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6],
                         name = 'name 1',legendgroup = 'name 1'),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70],
                         name = 'name 2', legendgroup = 'name 1', showlegend = False),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800],
                         name = 'name 3',legendgroup = 'name 3'),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000],
                        name = 'name 4', legendgroup = 'name 3', showlegend = False),
              row=2, col=2)
f = fig.full_figure_for_development(warn=False)
fig.show()