我试图改变颜色,以特定的变量stacked bar chart
中ggplot
。
我找到了此链接,但这不是我想要的。R ggplot更改堆积条形图中的一个变量的颜色
我想将Brand7
颜色更改为黑色,但其余品牌应使用不同的随机颜色进行着色。
我想要的是使用某种条件来为一个特定品牌选择颜色,而其他品牌可能像以前一样。
我也附上可复制的例子。
set.seed(1992)
n=8
Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Category, Brand, USD)
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')
您可以使用类似的方法,访问标准的ggplot颜色并替换所需的颜色。
用于访问ggplot-colors的功能,源
gg_color_hue <- function(n) {
hues = seq(15, 375, length=n+1)
hcl(h=hues, l=65, c=100)[1:n]
}
#make custom palette
mycols <- gg_color_hue(length(unique(df$Brand)))
names(mycols) <- unique(df$Brand)
mycols["Brand7"] <- "black"
#use palette in scale_fill_manual
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')+
scale_fill_manual(values=mycols)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句