问题
I am trying to build a visualization with plotly
combining multiple plots using subplot
. I'd like to have a legend that shows all levels from the various plots passed to subplot without duplicates.
Here is a simplified example of the problem:
library(plotly)
d <- data.frame(
x1 = c('a', 'a', 'b', 'b'),
x2 = c('a', 'b', 'b', 'c'),
y = 3 + runif(4)
)
p1 <- plot_ly(d[d$x1=='a', ], x=~x2, y=~y, color=~x2, type='bar', legendgroup=~x2)
p2 <- plot_ly(d[d$x1=='b', ], x=~x2, y=~y, color=~x2, type='bar', legendgroup=~x2, showlegend=F)
subplot(p1, p2, nrows=2)
The problem is that with showlegend=F
"c" does not appear in the legend, while with showlegend=T
"b" appears twice. I tried a couple of things such as adding "c" to p1
as an NA
value, but this is simply ignored by plotly. Also I tried adding a trace to p1
with all levels of the color with visible='legendonly'
but this messes up the plot a bit.
Is there any way to get all the unique entries from d$x2
in the legend without duplicates?
来源:https://stackoverflow.com/questions/62194528/display-all-levels-in-plotly-subplot-legend-without-duplicates