2

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

zimia
  • 930
  • 3
  • 16

1 Answers1

1

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • perfect. works like a charm and scales very well inside a shiny app – zimia Jul 06 '21 at 09:58
  • You are welcome. And if your are still in need of a color palette then maybe this is helpful: https://r-charts.com/color-palettes/#discrete. – stefan Jul 06 '21 at 10:04