Display all levels in plotly subplot legend without duplicates

 ̄綄美尐妖づ 提交于 2021-02-08 11:15:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!