首页 > 解决方案 > 如何使用 plotly subplots() 删除重复的图例条目

问题描述

使用 plotly 的 subplots() 时如何删除图例中的重复项?

这是我的 MWE:

library(plotly)
library(ggplot2)
library(tidyr)

mpg %>%
  group_by(class) %>%
  do(p = plot_ly(., x = ~cyl, y = ~displ, color = ~trans, type = 'bar')) %>%
  subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
  layout(barmode = 'stack')

标签: rggplot2plotlysubplotr-plotly

解决方案


plotly没有facet喜欢ggplot2,所以它会为每个添加图例,subplot或者您可以为其中一些关闭它。

在这里,我们没有包含所有~class条目的层,也没有两个没有交集的图,class其中它们的组合也覆盖了所有条目。在这种情况下,我们可以为那些特定的情节设置为,并将其设置showlegend为其余部分,并将其设置为,以便我们获得一个独特但完整的图例。TRUEFALSElegendgrouptrans

正如我所说,这里我们没有那种特殊情况。所以我能想到的有两种可能:

  1. 添加整个数据(复制整个数据框)并All为它们分配类。然后将其与原始数据一起绘制,但仅将图例保留为class == All.

  2. 使用ggplot::facet_wrapand thenggplotly来制作一个plotly对象。但是,这会导致一些问题x-axis(将对象与ggplot对象进行plotly比较)。

library(plotly)
library(ggplot2)
library(dplyr)
ly_plot <-  . %>% 
             plot_ly(x = ~cyl, y = ~displ, color = ~trans, 
                     type = 'bar', showlegend = ~all(legendC)) %>%
              add_annotations(
              text = ~unique(class),
              x = 0.5,
              y = 1,
              yref = "paper",
              xref = "paper",
              xanchor = "middle",
              yanchor = "top",
              showarrow = FALSE,
              font = list(size = 15))

mpg %>%
  mutate(class= "_All_") %>% 
  rbind(.,mpg) %>% 
  mutate(legendC = (class == "_All_")) %>% 
  group_by(class) %>%
  do(p = ly_plot(.)) %>%
  subplot(nrows = 2, shareX = TRUE, titleX = TRUE) %>%
  layout(barmode = 'stack')

#> Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, 
#>  allowed maximum for palette Set2 is 8
#> Returning the palette you asked for with that many colors

p <- ggplot(data = mpg, aes(x=cyl, y=displ, fill=trans))+
      geom_bar(stat="identity") +
      facet_wrap(~class)
p  

ggplotly(p) #seems for this we should also set "colour = trans"


推荐阅读