-1

I have data that has the following format:

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

Each row represents a revision of a document. The first column is the revision number, and the remaining columns represent elements added, removed, changed, and confirmed (ready) in the respective revision. (In reality, there are more rows and columns, this is just an example.) Each number represents the amount of recorded additions, removals, changes, and confirmations in each respective revision.

What I need is a stacked barplot that looks like somthing like this:

Example stacked barplot

I would like to do this in ggplot2. The exact visual look is not important (fonts, colours, and placement of the legend) as long as I can tweak it later. At the moment, it's the general idea I'm looking for.

I've looked at several questions and answers, e.g. How do I do a Barplot of already tabled data?, Making a stacked bar plot for multiple variables - ggplot2 in R, barplot with 3 variables (continous X and Y and third stacked variable), and Stacked barplot, but they all seem to make assumptions that don't match my data. I've also experimented with something like this:

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")

But obviously this does not create a stacked barplot because it just drawns the second geom_bar over the first.

How can I make a stacked barplot of my data using ggplot2?

Community
  • 1
  • 1
Fabian Fagerholm
  • 4,099
  • 1
  • 35
  • 45

1 Answers1

4

Try:

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

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

enter image description here

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • Amazing! I wasn't previously familiar with melt. Thank you! – Fabian Fagerholm Apr 19 '13 at 15:09
  • @FabianFagerholm FWIW, `melt` is the _first_ step taken in the accepted answer to one of the questions you say were no help. (The `stat = "identity"` piece is the only thing missing from that answer.) – joran Apr 19 '13 at 15:12
  • @joran: You're right – I was looking at the ggplot2 parts of the answers, trying to find a way to tell it what my data looked like. I didn't think the solution would lie in massaging the data to fit ggplot2's logic. Hopefully others will benefit from my mistake! – Fabian Fagerholm Apr 19 '13 at 15:14