[R] ggplot2: how to combine position=stack and position=dodge in a single graph?

Elena Schulz elena.schulz at gmx.net
Tue Oct 21 22:59:32 CEST 2008


Hi Hadley,

my problem is that I want to compare data for different years month by 
month. Each bar for a month is devided into two or more sections (-> 
stacking) By having all data of the same month right next to each other 
(-> dodging) comparision is much more easy than using faceting which 
does not show subtle differences within the same month of different 
years since all years get separated.

My approach to allow combining of stacking and dodging in a single
graphic would be the following:

# compare different years in one plot
# combine position_stack with position_dodge
ggplot() +
layer(data = nc_dat_06,
       mapping = aes(x=CommitMonth,
                 y=Price,
                 fill = factor(newCust),
                 width=0.4),
       geom="bar",
       colour="red",
       stat="identity"
       ) +
layer(data = nc_dat_07,
       mapping = aes(x=CommitMonth,
                 y=Price,
                 fill=factor(newCust),
                 width=0.4
                 ),
       geom="bar",
       colour="black",
       stat="identity"
       )

This works except that the second layer (data = nc_dat_07) is plotted 
right on top of the first one (data = nc_dat_06). If I could find a way 
to shift the whole second layer (data = nc_dat_07) a bit parallel to the 
x axis, I'm done. Is there an easy way for this? Adding an x-offset 
value to a layer?

Thanks for any help on this,

-- Elena


hadley wickham wrote:
> Hi Elena,
> 
> Currently, there's no way to combine stacking and dodging in a single
> graphic.  However, you can often use faceting to get a similar effect
> to dodging.  Could you explain your problem in a little more detail?
> 
> Thanks,
> 
> Hadley
> 
> On Sat, Oct 4, 2008 at 4:22 PM, Elena Schulz <elena.schulz at gmx.net> wrote:
>> Hi ggplot experts,
>>
>> I need to plot two time series of stacked data: a barchart with bars for
>> each month. To compare the data of two years I need to combine both time
>> series with in a single graph via position=doge.
>> How should I do that?
>>
>> I tried the following scenario:
>> I added two layers with the time series of the stacked data for both years.
>> That worked well exept the bars are obscuring each other. How can  I shift
>> one of the layers to get them displayed next to each other.
>>
>> Is there an other easier way to achieve this?
>>
>> Thanks a lot for any help on this.
>>
>> -- Elena
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
> 
> 
>



More information about the R-help mailing list