2015-12-21 264 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