我有以下与plotly的情节:
library(plotly)
library(dplyr)
ggplot2::diamonds %>% count(cut, clarity) %>%
plot_ly(x = ~cut, y = ~n, color = ~clarity,colors = 'Blues')
现在,对于所有群组,我只有一个调色板“蓝色”。我该如何自定义它,以便每组只有一个调色板? 例如,我想要调色板
答案 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()
这是结果:
相应的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)