2017-03-18 109 views
0

我想生成一個條形圖與ggplot2其中一個單一的酒吧是用指定的顏色分離。ggplot使用geom_bar - 區分單色條與顏色

要使用一個簡單的數據幀說明:

type <- c('apples','pears','bananas','plums','melons','pineapples') 
weight <- c(14,11,19,16,12,8) 
fruit <- data.frame(type,weight) 

這是我迄今爲止生產的情節:

library("ggplot2") 
f <- ggplot(fruit, aes(x=type, y=weight)) 

f + geom_bar(stat=’identity", fill = (ifelse(fruit$type=='bananas', 'yellow', 'gray'))) 
+0

OK,所以有什麼問題呢? (除了你的''',而不是''') – Axeman

+0

我得到'甜瓜'填充爲黃色時,它應該是'香蕉' – Curious56

+2

好吧。嘗試'f + geom_col(aes(fill = ifelse(fruit $ type =='bananas','yellow','gray')))+ scale_fill_identity()' – Axeman

回答

1

的ggplot巴的依賴的順序上您的因子變量的水平爲fruit$type

更換你用下面的工作最後一行,因爲我們需要的因子水平是香蕉:

f + geom_bar(stat="identity", fill = (ifelse(levels(fruit$type)=='bananas', 'yellow', 'gray'))) 
+0

Axeman's和Robert的解決方案都很好,非常感謝。 – Curious56