2017-09-26 59 views
1

我想在ggplot中的顏色條,但有問題。有人可以解釋如何正確使用fill參數和scale_colour參數嗎?在ggplot填充和scale_color

library(ggplot2) 

df<-data.frame(c(80,33,30),c("Too militarized","Just doing their job","Unfairly tarnished by a few"),c("57%","23%","21%")) 
colnames(df)<-c("values","names","percentages") 

ggplot(df,aes(names,values))+ 
    geom_bar(stat = "identity",position = "dodge",fill=names)+ 
    geom_text(aes(label=percentages), vjust=0)+ 
    ylab("percentage")+ 
    xlab("thought")+ 
    scale_colour_manual(values = rainbow(nrow(df))) 

工作barplot例如

barplot(c(df$values),names=c("Too militarized","Just doing their job","Unfairly tarnished by a few"),col = rainbow(nrow(df))) 

回答

1

的主要問題是,你不必fillgeom_bar()aes通話中。從數據映射到顏色等視覺效果時,必須在aes()之內。

選項1(沒有說明)::您可以通過包裹fill=namesaes()或通過僅指定直接填充顏色,而不是使用names解決這個

ggplot(df, aes(names, values)) + 
    geom_bar(stat="identity", fill=rainbow(nrow(df))) + 
    ylab("percentage") + 
    xlab("thought") 

選項2(圖例,因爲從數據映射將顏色):

ggplot(df, aes(names, values)) + 
    geom_bar(stat="identity", aes(fill=names)) + 
    ylab("percentage") + 
    xlab("thought") + 
    scale_fill_manual(values=rainbow(nrow(df))) 

注意,在這兩種情況下,你可能要爲了得到你的順序W上的條明確因素df$names提前調用到ggplot螞蟻。

+0

感謝您提供這兩種解決方案,真的有幫助! – Rilcon42