2016-05-31 209 views
0

我想獲得一個條形圖,其中條形高度與總值相對應,並且條形本身根據部分值分爲顏色。如何使用ggplot2繪製帶有顏色填充的geom_bar圖形data_frame

df <- data.frame(name = c("a", "b", "c"), 
       total = c(10, 20, 30), 
       left = c(5, 10, 5), 
       middle = c(4, 5, 15), 
       right = c(1, 5, 10)) 

df <- gather(df, key, value, 3:5) 

ggplot(df, aes(x = name, y = total, fill = key)) + geom_bar(stat = "identity") 

我得到不尊重局部值的分佈......

+1

'y = value'時怎麼樣? – mtoto

回答

1

變化總在ggplot值:

ggplot(df, aes(x = name, y = value, fill = key)) + geom_bar(stat = "identity") 

代替:

ggplot(df, aes(x = name, y = total, fill = key)) + geom_bar(stat = "identity")