繁体   English   中英

R - Plotly 几个调色板分组栏

[英]R - Plotly several color palettes grouped bar

我有以下情节与 plotly :

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

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

  • “蓝调”为“公平”级别
  • “绿色”代表“好”级别
  • “非常好”级别的“红色”
  • “高级”级别的“紫色”
  • “理想”级别的“灰色”

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

在此处输入图片说明

暂无
暂无

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

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