簡體   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