如何使用plotly subplots()删除重复的图例条目

bla*_*ath 11 r ggplot2 subplot plotly r-plotly

使用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')
Run Code Online (Sandbox Code Playgroud)

M--*_*M-- 5

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

在这里,我们没有一个包含所有~class条目的图层,也没有两个没有交集的地块class,它们的组合也覆盖了所有地块。在这种情况下,我们可以设置showlegendTRUE这些特定的情节(S)并将其设置为FALSE在休息,并设定了legendgrouptrans,所以我们得到一个唯一的,但也完整的传奇。

正如我所说,这里没有特殊情况。因此,我想到的是两种可能性:

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

  2. ggplot::facet_wrap然后使用ggplotly制作plotly对象。但是,这会引起一些问题x-axis(将ggplot对象与对象进行plotly比较)。

library(plotly)
library(ggplot2)

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
Run Code Online (Sandbox Code Playgroud)

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

ggplotly(p) #seems for this we should also set "colour = trans"
Run Code Online (Sandbox Code Playgroud)


Jor*_*hau 4

另一种解决方法是使用tidyverse. 在原来的MWE的基础上增加了以下步骤:

  • trans列转换为因子。
  • 使用 tidyr'scomplete填充每组中缺失因子水平的(非 NA)虚拟值class
  • 按照 MM 的建议设置showlegendTRUE设置单个组并legendgroup链接trans子图之间的图例条目。
library(plotly)
library(tidyverse)

mpg %>%
    mutate_at("trans", as.factor) %>%  
    group_by(class) %>%
    group_map(.f = ~{          
          ## fill missing levels w/ displ = 0, cyl = first available value 
          complete(.x, trans, fill = list(displ = 0, cyl = head(.x$cyl, 1))) %>%
          plot_ly(x = ~cyl, y = ~displ, color = ~trans, colors = "Paired", type = "bar",
              showlegend = (.y == "2seater"), legendgroup = ~trans) %>%
          layout(yaxis = list(title = as.character(.y)), barmode = "stack")
        }) %>%
    subplot(nrows = 2, shareX = TRUE, titleY = TRUE) 
Run Code Online (Sandbox Code Playgroud)

情节图