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:
- Stacking (HFGroup): have phase II on top of phase I
- 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.
You can't have both
position_dodge
andposition_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 ofHFGroup
, and filling byHFGroup
. You then makeQuantGroup
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: