繁体   English   中英

绘制具有相同颜色的子图线

[英]plotly subplot lines with same color

我有一些跨多个类别的时间序列数据,其中每个类别都有一组产品的子集,我想将它们绘制在一个可绘制的子图中,以便每个产品线具有相同的颜色。 我该怎么做呢?

我尝试在颜色参数中指定一个不起作用的调色板,我还尝试使用expand_grid用缺少的产品“填充”每个类别,但这也不起作用。 最后我尝试了两种方法的组合,但仍然无效。

以下是该问题的玩具数据集。 正如您在图例组中看到的那样,每个类别的线条颜色不同。

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)

在此处输入图片说明

您可以使用颜色向量的命名向量为您的产品分配颜色并将其传递给plot_lycolors参数, plot_ly所示:

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)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM