If you have to diagrams in one figure you can group the legend according to the related sub-plots by means of the feature legendgroup
. Unfortunately, this breaks in my example below the interactive functionality to toggle visibility of individual traces, has someone an idea how to fix this?
using PlotlyJS
function _legend_groups()
# ---
# --- create object containing sub-plots():
_fig_obj = PlotlyJS.make_subplots(
rows = 1, cols = 2,
# column 1 column 2
specs = [ Spec() Spec()], # raw 1
)
# --- read vector of standard colors "colorway":
_colorway = PlotlyJS.PlotlyBase._get_colorway(_fig_obj.plot) # we must take the field ".plot"
# ---
_fig_layout = PlotlyJS.Layout(;
title_text = "Legend Groups",
xaxis_title_text = "time / s",
yaxis_title_text = "Amplitude",
yaxis_range = [0, 4],
yaxis2 = PlotlyJS.attr(
title = "Amplitude",
overlaying = "y",
side = "left",
range = [0, 4],
scaleanchor = "y",
scaleratio = 1,
),
xaxis2_title_text = "time / s",
)
# ---
for i_segment = 1 : 3
if i_segment == 1
PlotlyJS.add_trace!(_fig_obj, PlotlyJS.scatter(; y = i_segment .* ones(4),
line_color = _colorway[i_segment],
legendgroup = "group1", legendgrouptitle_text="First Group Title", ), row = 1, col =1)
PlotlyJS.add_trace!(_fig_obj, PlotlyJS.scatter(; y = 1.1 * i_segment .* ones(4),
line_color = _colorway[i_segment],
legendgroup = "group2", legendgrouptitle_text="Second Group Title", ), row = 1, col =2)
else
PlotlyJS.add_trace!(_fig_obj, PlotlyJS.scatter(; y = i_segment .* ones(4),
line_color = _colorway[i_segment], legendgroup = "group1", ), row = 1, col =1)
PlotlyJS.add_trace!(_fig_obj, PlotlyJS.scatter(; y = 0.5 * i_segment .* ones(4),
line_color = _colorway[i_segment], legendgroup = "group2", ), row = 1, col = 2)
end
end
# ---
PlotlyJS.relayout!(_fig_obj.plot, _fig_layout) # only re-layout the field ".plot"
return _fig_obj
end
display(_legend_groups().plot)