William Gunn
William Gunn

Reputation: 2995

How can I add facets to my ggplot2 stacked bar graph?

With data that looks like this:

Subcategory    Title   Value
Sub1           Name1   2 
Sub1           Name2   5
Sub2           Name3   4
Sub2           Name4   1
Sub3           Name5   2
Sub3           Name6   7
Sub4           Name1   7
Sub4           Name2   5
Sub5           Name3   4
Sub5           Name4   3
Sub6           Name5   9
Sub6           Name6   1
...            ...     ...

I can make a graph that looks like this:

Using this code: p <- ggplot(data=dat, aes(x=Title, y=Value, fill=Subcategory)) + geom_bar(position="stack", stat="identity") + coord_flip()

How do I present the data using facets instead of a stacked bar, as Mr. Hadley did in his geom_bar example? http://had.co.nz/ggplot2/geom_bar.html I'm a bit lost where it comes to facets and ~ notation, so I'm mostly looking for examples to help me understand. If you know of other good examples, please share.

Upvotes: 2

Views: 5251

Answers (1)

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44638

p <- ggplot(data=dat, aes(Title, Value)) 
+ geom_bar(position="stack", stat="identity") 
+ coord_flip() + facet_wrap(~Subcategory)

You don't need to specify x and y. aes() assumes that they are provided in that order. If you're faceting, you generally don't fill by the facet otherwise things will look the same.

Upvotes: 3

Related Questions