Search code examples
rcolorsplotlyr-plotlypalette

plotly subplot lines with same color


I have some time series data across multiple categories, where each category has a subset of a group of products and I want to plot them in a plotly subplot so each product line has the same color. How do I do this?

I have tried specifying a palette in the colors argument which did not work, and I also tried using an expand_grid to "pad" each category with the missing products, but that also did not work. And finally I tried a combination of both approaches which still did not work.

Below is a toy dataset of the problem. As you can see in the legendgroup the lines for each category are coloured differently.

data <- expand_grid(Category = c(LETTERS[1:3]), Product = letters[1:5], date = seq.Date(as.Date("2020-01-01"), as.Date("2020-12-31"), by = 7)) %>% 
  mutate(y_value = rnorm(nrow(.), 50, 25)) %>% 
  filter(!paste0(Category, Product) %in% c("Ab","Bd","Ce","Ca"))

data %>% 
  group_by(Category) %>% 
  do(
    plot = plot_ly(data = ., x=~date, y = ~ y_value, color = ~Product, legendgroup = ~ Product) %>% 
      add_lines(hoverinfo = "text", text = ~ paste0("Category: ", Category, "<br>", "Product: ", Product)) %>% 
      add_annotations(text = ~Category, x = 0.5,y = ~ max(y_value), xref = "paper",showarrow = FALSE)
  ) %>% 
  subplot(nrows = 3, shareX = TRUE, shareY = FALSE)

enter image description here


Solution

  • You could make use of a named vector of color vectors to assign colors to your products and passing it to the colors argument of plot_ly like so:

    library(plotly)
    library(tidyr)
    
    data <- expand_grid(Category = c(LETTERS[1:3]), Product = letters[1:5], date = seq.Date(as.Date("2020-01-01"), as.Date("2020-12-31"), by = 7)) %>% 
      mutate(y_value = rnorm(nrow(.), 50, 25)) %>% 
      filter(!paste0(Category, Product) %in% c("Ab","Bd","Ce","Ca"))
    
    colors <- c("a" = "blue", "b" = "red", c = "green", d = "orange", e = "purple")
    data %>% 
      group_by(Category) %>% 
      do(
        plot = plot_ly(data = ., x=~date, y = ~ y_value, color = ~Product, colors = colors, legendgroup = ~ Product) %>% 
          add_lines(hoverinfo = "text", text = ~ paste0("Category: ", Category, "<br>", "Product: ", Product)) %>% 
          add_annotations(text = ~Category, x = 0.5,y = ~ max(y_value), xref = "paper",showarrow = FALSE)
      ) %>% 
      subplot(nrows = 3, shareX = TRUE, shareY = FALSE)
    

    enter image description here