1

Spoiler: This post is related to this one, but I am looking for an automated way to solve the following problem: I want to plot a list of matrices, where each matrix is plotted as a subplot. The columns in each matrix (plotted as lines) correspond with each other, so I would like them to appear with the same color, the same legend entry, and I would like to toggle them on or off simultaneously. I came up with the following solution (using this thread) but I wonder if there is a more elegant way to do it:

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

# create data
subject_matrices = [np.random.rand(3,3),np.random.rand(3,3),np.random.rand(3,3)]

# plotting preparation
colors = plotly.colors.DEFAULT_PLOTLY_COLORS
fig = make_subplots(rows=1,cols=3)
subplot_indices = [(1,1),(1,2),(1,3)]
region_indices = [0,1,2]
labels = ['r1','r2','r3']

# plot each matrix as a subplot
for matrix,(row,col) in zip(subject_matrices,subplot_indices):
    for idx,region_idx in enumerate(region_indices):
        trace = go.Scattergl(y=matrix[:,region_idx],
                             line=dict(color=colors[idx]),
                             legendgroup=labels[region_idx],
                             name=labels[region_idx],
                             )
        fig.append_trace(trace,row,col)

# delete duplicate legend entries
names = set()
fig.for_each_trace(
    lambda trace:
        trace.update(showlegend=False)
        if (trace.name in names) else names.add(trace.name))

fig.show(renderer='browser')

Note: I know that I could probably solve this by using plotly.express but this would require me to put all the matrices in one long-format data frame, which (at least in my case) can get very computationally expensive. Besides, I would like to benefit from the speed provided by plotly.graph_objects.Scattergl

Johannes Wiesner
  • 1,006
  • 12
  • 33

0 Answers0