[R] ggplot2: how to combine position=stack and position=dodge in a single graph?
h.wickham at gmail.com
Tue Oct 28 16:12:38 CET 2008
On Fri, Oct 24, 2008 at 5:18 PM, Elena Schulz <elena.schulz at gmx.net> wrote:
> Hi Hadley,
> thanks a lot for your quick answer.
>> You should be able to replicate any dodging layout with facetting
> You mean instead of facetting by years, facetting by months? I will try this
> an see how the plot looks.
I'd do it like this:
ggplot(nc_dat, aes(CommitYear, Price, fill = newCust)) + geom_bar(stat
= "identity") + facet_grid(. ~ CommitMonth) +
Although for more years, I'd think this would be better:
ggplot(nc_dat, aes(as.numeric(as.character(CommitYear)), Price, fill =
newCust)) + geom_area(position = "stack") + facet_grid(. ~
CommitMonth) + scale_x_continuous(breaks = 2006:2007, labels = c("06",
But generally, I'm not a big fan of stacking, because you can only
accurately see cumulative sums, not the contributions of individual
>> shift the second layer across a bit
>> with aes(x=as.numeric(CommitMont) + 0.5)).
> I tried this, but it didn't work with my data. I think due to the fact that
> I am quite new to R.
>> please send me a reproducible example.
> It took me a bit to create some reproducible example data that shows my
> problem. Please see the example script below.
Ok, so there's a couple of bugs in ggplot2 that make this not work
very well. The best you can do is:
ggplot(nc_dat_06, aes(CommitMonth, Price, fill = newCust, width = 0.4)) +
geom_bar(aes(as.numeric(CommitMonth) - 0.20), colour="red", stat="identity") +
geom_bar(aes(as.numeric(CommitMonth) + 0.20), data=nc_dat_07,
colour="red", stat="identity") + scale_x_discrete(breaks=1:12)
(note the absence of labels on the x axis). I'll have look into this
and see that it gets fixed for the next version.
> Wouldn't it be more intuitive to have some parameters for layers like
> stacking=c(s1, s2, ...), dodging=c(d1, d2), ..., or is the combination of
> both so rarely used?
It's rarely used, only works with bars, can be replicated closely with
facetting, and (in my opinion) is not a very effective display.
More information about the R-help