2015-12-21 261 views
1

我想将颜色更改为stacked bar chart中的特定变量ggplot更改特定变量R ggplot的颜色堆积条形图

我找到了这个链接,但它不是我想要的。 R ggplot Changing color of one variable in stacked bar graph

我想将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') 
+0

检查'?scale_colour_manual' –

+0

的品牌数量总是变化,我想改变为唯一品牌。在一个案例中,可能有1个品牌,其他案例100个 – AK47

回答

3

你可以使用类似的东西,访问标准的ggplot-colors并替换你需要的。

功能访问ggplot,颜色,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) 

enter image description here