[R] ggplot2: how to combine position=stack and position=dodge in a single graph?
Elena Schulz
elena.schulz at gmx.net
Sat Nov 8 14:01:01 CET 2008
Hi Hadley,
thanks for your hints and sorry for my late answer.
I will check them and see whether they will help in my case.
Unfortunately I found some nasty data import problems that I have to
solve before I can continue with the graphics. (encoding problems)
For me the reason for combining dodging and stacking is that it shows
the relation of the totals quite accurately and at the same time gives
some hints about the quantity of contributions of the underlying
factors. This type of display is very easy to understand by people using
MSExcel.
-- Elena
hadley wickham wrote:
> 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) +
> scale_x_discrete(labels=c("06", "07"))
>
> 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",
> "07"))
>
> But generally, I'm not a big fan of stacking, because you can only
> accurately see cumulative sums, not the contributions of individual
> components.
>
>>> 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.
>
> Hadley
>
More information about the R-help
mailing list