首页 > 解决方案 > R - Plotly 几个调色板分组栏

问题描述

我有以下情节:

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

现在我只有一个调色板'蓝色'适用于所有组。如何自定义它,以便每组有一个调色板?例如,我想要调色板

标签: rbar-chartplotlycolor-palette

解决方案


以下代码似乎适用于静态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()

这是结果:

在此处输入图像描述

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

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

在此处输入图像描述

然而事实证明,这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)

在此处输入图像描述


推荐阅读