Search code examples
rggplot2plotlysubplotr-plotly

How to remove duplicate legend entries w/ plotly subplots()


How can I remove the duplicates in my legend when using plotly's subplots()?

Here is my 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')

Solution

  • Another workaround using the tidyverse. The following steps are added to the original MWE:

    • Convert the trans column to a factor.
    • Use tidyr's complete to fill (non-NA) dummy values for the missing factor levels in each class group.
    • Follow M-M's suggestion setting showlegend to TRUE for a single group and legendgroup to trans to link the legend entries between subplots.
    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) 
    

    plotly_plot