2011-07-14 70 views
8

我在ggplot2中制作堆叠条形图时遇到了一些问题。我知道如何用barplot()创建一个,但是我想使用ggplot2,因为它很容易让bar具有相同的高度('position ='fill'',如果我没有弄错的话)。为多个变量制作堆叠条形图 - g中的ggplot2

我的问题是,我有多个变量,我想绘制在彼此的顶部;我的数据看起来像这样:

dfr <- data.frame(
    V1 = c(0.1, 0.2, 0.3), 
    V2 = c(0.2, 0.3, 0.2), 
    V3 = c(0.3, 0.6, 0.5), 
    V4 = c(0.5, 0.1, 0.7), 
    row.names = LETTERS[1:3] 
) 

我想是与类别的曲线A,B,和C在X轴上,并且对于每个那些,对于V1,V2,V3和V4堆叠的值在Y轴上彼此重叠。我所看到的大多数图表在Y轴上只绘制了一个变量,但我确信某人可以以某种方式做到这一点。

我怎样才能做到这一点与ggplot2?谢谢!

+0

+1用于添加样本数据。欢迎来到SO。 – Andrie

+0

如果您发现任何有用的答案,请选择一个作为您接受的答案。 –

回答

15

首先进行一些数据操作。将类别添加为变量并将数据融化为长格式。

dfr$category <- row.names(dfr) 
mdfr <- melt(dfr, id.vars = "category") 

现在的情节,使用命名variable来确定每个栏的填充颜色的变量。

library(scales) 
(p <- ggplot(mdfr, aes(category, value, fill = variable)) + 
    geom_bar(position = "fill", stat = "identity") + 
    scale_y_continuous(labels = percent) 
) 

(编辑:代码更新为使用scales软件包,因为GGPLOT2 V0.9根据需要)

enter image description here

+0

+1当我刚刚发布相同的内容时,你就击败了! –

+0

@lselzer,伟大的思想家一样思考!国际海事组织,下一次,你应该毫不犹豫地发布你的答案,即使非常相似。 –

+0

非常感谢Richie!这对我有用。我有一个问题,但如果我用'p < - ggplot(mdfr,aes(category,value,fill = variable,position ='fill'))+ + geom_bar()'杆不向上延伸以具有相同的高度。为了让情节做到这一点,我需要做其他事吗?谢谢! – Annemarie

3

请原谅我开始一个新的答案,而我真的只是想添加一个评论@Richie提供的美丽解决方案。我没有最小的点发表评论,所以这里是我的情况:

... + geom_bar(position="fill")为我的绘图抛出一个错误,我使用的ggplot2版本0.9.3.1。并重塑2,而不是重塑融化。

error_message: 
*Mapping a variable to y and also using stat="bin". 
    With stat="bin", it will attempt to set the y value to the count of cases in each group. 
    This can result in unexpected behavior and will not be allowed in a future version of ggplot2. 
    If you want y to represent counts of cases, use stat="bin" and don't map a variable to y. 
    If you want y to represent values in the data, use stat="identity". 
    See ?geom_bar for examples. (Deprecated; last used in version 0.9.2) 
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this. 
Error in pmin(y, 0) : object 'y' not found* 

所以我将它改为geom_bar(stat='identity'),它工作。

+0

感谢您发表这个消息,我无法弄清楚如何解决这个错误! –

相关问题