繁体   English   中英

更改特定变量R ggplot堆积条形图的颜色

[英]Change color for specific variable R ggplot Stacked Bar chart

我正在尝试将颜色更改为ggplotstacked bar chart特定变量。

我找到了这个链接,但这不是我想要的。 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-colors并替换你需要的颜色。

访问ggplot-colors, source的函数

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)

在此输入图像描述

暂无
暂无

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

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