Boboh
Boboh

Reputation: 23

Creating a side by side bar plot with 1 continuous variable and 2 factor variables (one for stacking and the other for grouping bars)

I have a dataframe in long format as follows (sample):

QuarterPeriod <- c(rep("2011_Q1",4), rep("2011_Q2",4), 
                   rep("2011_Q3",4), rep("2011_Q4",4), 
                   rep("2012_Q1",4), rep("2012_Q2",4))
HFGroup <- c(rep(c("Phase I","Phase II"),12))
QuantGroup <- c(rep(c(rep("Declared", 2), 
                      rep("Verified", 2)),6))
Values <- c(sample.int(25:100, 24))

df <- as.data.frame(cbind(QuarterPeriod, HFGroup,
                          QuantGroup,Values))

and I have the following code to create 2 bar charts using one factor variable for facetting and another to group bars within the plots:

require(ggplot2)
ggplot(data=df,
       aes(x=QuarterPeriod, y= Values,
           fill=QuantGroup)) +
  geom_bar(stat="identity", position=position_dodge()) +
  facet_wrap(~HFGroup)

Instead of using facetting to get 2 plots, I want 1 plot whereby the 2 factor variables (QuantGroup and HFGroup) are used for:

  1. Stacking (HFGroup): have phase II on top of phase I
  2. Grouping (QuantGroup): Have Declared and Verified data for the same quarter be plotted side by side.

At the end, for say 2011_Q1, there should be 2 bars (one for declared data and another for verified data) but each bar should be showing phase I & II stacked on top of each other.

Upvotes: 0

Views: 232

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174586

You can't have both position_dodge and position_stack on a bar graph, so you need to get creative. You can get the effect you are looking for by faceting on quarter instead of HFGroup, and filling by HFGroup. You then make QuantGroup your x axis. This gives you a 2-column stacked bar for each quarter. You then just adjust the facets so that they don't look like facets by reducing their spacing to zero and bringing the strips to the bottom:

ggplot(df, aes(QuantGroup, Values, fill = HFGroup)) +
  geom_col() +
  facet_grid( ~ QuarterPeriod, switch = "x") +
  xlab("Quant Group by Quarter") +
  theme(panel.spacing    = unit(0, "points"),
        strip.background = element_blank(),
        strip.placement  = "outside")

enter image description here

Upvotes: 2

Related Questions