R-绘制多个调色板分组条形图

时间:2019-01-09 16:35:28

标签: r bar-chart plotly color-palette

我有以下与plotly的情节:

library(plotly)
library(dplyr)
ggplot2::diamonds %>% count(cut, clarity) %>%
  plot_ly(x = ~cut, y = ~n, color = ~clarity,colors = 'Blues')

现在,对于所有群组,我只有一个调色板“蓝色”。我该如何自定义它,以便每组只有一个调色板? 例如,我想要调色板

  • “蓝色”代表“公平”级别
  • “绿色”等级为“好”
  • “红色”级别为“很好”
  • “紫色”代表“高级”级别
  • “灰色”代表“理想”级别

1 个答案:

答案 0 :(得分:1)

以下代码似乎适用于静态ggplot2情节:

library(tidyverse)
library(plotly)
library(RColorBrewer)

sPalette <- c("Blues", "Greens", "Reds", "Purples", "Greys") %>% 
              sapply(., function(x) brewer.pal(8, name = x)) %>% 
              as.vector

diamonds %>% 
  count(cut, clarity) %>% 
  ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_fill_manual(values = sPalette, guide = F) + 
    theme_minimal()

这是结果:

enter image description here

相应的plot_ly代码产生的条形图之间有很大的间隔,我不确定为什么会这样:

diamonds %>% 
  count(cut, clarity) %>%
  plot_ly(x = ~cut, y = ~n, color = ~interaction(clarity, cut, sep = " - ") , colors = sPalette)

enter image description here

然而,事实证明ggplotly确实有效:

p <- diamonds %>% 
       count(cut, clarity) %>% 
       ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) + 
         geom_bar(stat = "identity", position = "dodge") + 
         scale_fill_manual(values = sPalette, guide = F) + 
         theme_minimal()
ggplotly(p)

enter image description here