如何使用ggplot2制作预先存储数据的堆积条形图,每列是每个条形图的一个因素?

时间:2013-04-19 14:56:50

标签: r graphics ggplot2

我的数据格式如下:

revision    added    removed    changed    confirmed
1           20       0          0          0
2           18       3          8          10
3           12       8          14         10
4           6        5          11         8
5           0        1          7          11

每行代表文档的修订版。第一列是修订号,其余列表示在相应修订中添加,删除,更改和确认(就绪)的元素。 (实际上,有更多的行和列,这只是一个示例。)每个数字代表每个相应修订版中记录的添加,删除,更改和确认的数量。

我需要的是一个堆积的条状图,看起来像这样:

Example stacked barplot

我想在ggplot2中这样做。只要我稍后可以调整它,确切的视觉外观并不重要(字体,颜色和图例的位置)。目前,这是我正在寻找的一般想法。

我看过几个问题和答案,例如: How do I do a Barplot of already tabled data?Making a stacked bar plot for multiple variables - ggplot2 in Rbarplot with 3 variables (continous X and Y and third stacked variable),和 Stacked barplot,但他们似乎都做出了与我的数据不符的假设。我也尝试过这样的事情:

ggplot(data) + geom_bar(aes(x=revision, y=added), stat="identity", fill="white", colour="black") + geom_bar(aes(x=revision, y=removed), stat="identity", fill="red", colour="black")

但显然这并没有创建堆叠的条形图,因为它只会在第一个上绘制第二个geom_bar

如何使用ggplot2制作数据的堆积条形图?

1 个答案:

答案 0 :(得分:4)

尝试:

library(reshape2)
dat <- melt(data, id="revision")

ggplot(dat, aes(x=revision, y=value, fill=variable)) +
  geom_bar(stat="identity")

enter image description here