2016-05-31 206 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")