简体   繁体   English

使用子图时控制ggplotly中的图例

[英]Control legend in ggplotly when using subplot

I use the R plotly package and the functions ggplotly and subplot to create an interactive plot consisting of multiple individually interactive ggplot2 plots.我使用R plotly包和功能ggplotlysubplot以创建由多个单独的交互的交互积ggplot2图。 Some of the plots share the same grouping variables.一些图共享相同的分组变量。

col <- factor(rep(c(1, 2), 5))
fill <- factor(c(rep("a", 5), rep("b", 5)))
x1 <- x2 <- y1 <- y2 <- 1:10
x3 <- y3 <- 11:20
d1 <- dplyr::tibble(x1 = x1, y1 = y1, col = col)
d2 <- dplyr::tibble(x2 = x2, y2 = y2, col = col, fill = fill)
d3 <- dplyr::tibble(x3 = x3, y3 = y3, col = col)

g1 <- 
  ggplot2::ggplot(d1) + 
  ggplot2::geom_point(ggplot2::aes(x = x1, y = y1, col = col))

g2 <- 
  ggplot2::ggplot(d2) + 
  ggplot2::geom_point(ggplot2::aes(x = x2, y = y2, col = col, fill = fill)) + 
  ggplot2::scale_fill_manual(values = c("red","green")) 

g3 <- 
  ggplot2::ggplot(d3) + 
  ggplot2::geom_point(ggplot2::aes(x = x3, y = y3, col = col))

plotly::subplot(plotly::ggplotly(g1), plotly::ggplotly(g2), plotly::ggplotly(g3))

在此处输入图片说明

1) How can I remove the duplicated "col" labels in the interactive plotly legend? 1)如何删除交互式plotly图例中重复的“col”标签?

2) How can I remove the legend for "fill", but keep the legend for "col"? 2)如何删除“fill”的图例,但保留“col”的图例?


EDIT: I know about the following "dirty" solution, which is to manually disable the legend:编辑:我知道以下“脏”解决方案,即手动禁用图例:

t <- 
plotly::subplot(plotly::ggplotly(g1), plotly::ggplotly(g2), plotly::ggplotly(g3))

t$x$data[[1]]$showlegend <- FALSE
t$x$data[[2]]$showlegend <- FALSE
t$x$data[[3]]$showlegend <- FALSE
t$x$data[[4]]$showlegend <- FALSE

However, this requires me to know the positions of the list elements in advance, which is why I am looking for a more general solution.但是,这需要我提前知道列表元素的位置,这就是为什么我要寻找更通用的解决方案。

Another way to manually remove the unwanted legends is to use style() .手动删除不需要的图例的另一种方法是使用style() In your example, lt <- t %>% style(t, showlegend = FALSE, traces = 3:n) , where n<-8 is defined before, will suppress the unwanted legends.在您的示例中, lt <- t %>% style(t, showlegend = FALSE, traces = 3:n) ,其中n<-8之前定义,将抑制不需要的图例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM