在绘图图表中为各个迹线设置特定的调色板

时间:2017-08-02 14:11:36

标签: r plotly

我正在尝试为图表中每个单独的轨迹定义一个特定的调色板。我的代码如下:

library(ggplot2)
library(dplyr)
library(plotly)
colors_1 <- c("#2e71c9","#ffb728")
colors_2 <- c("#4f4f4f","#000000")

data_subset_1 <- 
    diamonds %>% 
    filter(clarity %in% c("VVS2", "VS1")) %>% 
    mutate(cut = as.character(cut)) %>% 
    count(cut, clarity)

data_subset_2 <- 
    diamonds %>% 
    filter(clarity %in% c("SI1", "IF")) %>% 
    mutate(cut = as.character(cut)) %>% 
    count(cut, clarity)

plot_ly() %>% 
    add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = colors_1) %>% 
    add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity, colors = colors_2)

第一条痕迹的条纹应为蓝色和橙色,第二条痕迹为灰色和黑色,但显然它们都是彩色的。如果我从第二个跟踪中删除colors = colors_2,它甚至根本不会改变任何内容。似乎第一条轨迹中定义的颜色用于计算用于绘图的所有轨迹的调色板,但我想专门指定调色板。

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

cols <- setNames(c("#2e71c9","#ffb728", "#CCDDDD","#000000"), 
                 c("VVS2", "VS1", "SI1", "IF"))

plot_ly() %>% 
  add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = cols) %>% 
  add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity)

enter image description here