Plotlyjs - merged legend for both subplots

Hi, this is followup of Plotly.js - stacked bars in subplots - #3 by stej

I have this code

###########

using PlotlyJS, Dates

dates = [Date(2021, 05, 08), Date(2021, 05, 09), Date(2021, 05, 10)]
trace1 = bar(; x = dates, y = [15, 1, 6], name = "Buy - euro", barmode="stack")
trace2 = bar(; x = dates, y = [2, 5, 4], name = "Buy - usd", barmode="stack")
tracesBuy = [trace1, trace2]

p1 = plot(tracesBuy, Layout(;barmode="stack", title="Buy"))

trace3 = bar(; x = dates, y = [-10, -5, -8], name = "Sell - euro", barmode="stack")
trace4 = bar(; x = dates, y = [-15, -6, -3], name = "Sell - usd", barmode="stack")
tracesSell = [trace3, trace4]
p2 = plot(tracesSell, Layout(;barmode="stack", title="Sell"))
p = [p1, p2]
p.plot.layout["barmode"] = "stack"
p

The result looks like this

Is it somehow possible to have merged legend and the related bars to have the same color?

E.g.

  • bars for EUR red in both subplots
  • bars for USD blue in both subplots
  • the legend just contains 2 lines: USD, EUR and is clickable
    → if I click USD, just USD bars will be visible in both subplots

Is that even possible?
Thanks a lot!

Try something like

tr6 = scatter(b2, x = :tag, y = :loess, group = :variable, legendgroup = (df) -> df[1,:variable], line_color = (df) -> df[1,:variable])
1 Like

To show better what I’d like.

After rendering:

If I don’t want to show “usd”, just “euro”:

Applying my snippet to your code yields

using PlotlyJS, Dates

dates = [Date(2021, 05, 08), Date(2021, 05, 09), Date(2021, 05, 10)]
trace1 = bar(; x = dates, y = [15, 1, 6], name = "Buy - euro", barmode="stack", legendgroup = "euro", marker_color = "Orange")
trace2 = bar(; x = dates, y = [2, 5, 4], name = "Buy - usd", barmode="stack", legendgroup = "usd", marker_color = "Green")
tracesBuy = [trace1, trace2]

p1 = plot(tracesBuy, Layout(;barmode="stack", title="Buy"))

trace3 = bar(; x = dates, y = [-10, -5, -8], name = "Sell - euro", barmode="stack", legendgroup = "euro", showlegend = false, marker_color = "Orange")
trace4 = bar(; x = dates, y = [-15, -6, -3], name = "Sell - usd", barmode="stack", legendgroup = "usd", showlegend = false, marker_color = "Green")
tracesSell = [trace3, trace4]
p2 = plot(tracesSell, Layout(;barmode="stack", title="Sell"))
p = [p1, p2]
p.plot.layout["barmode"] = "stack"
p
2 Likes

Great, thanks! Exactly what I was looking for. I expected the solution will be more complicated. It looks like there is a lot of magic inside the library… :slight_smile: