Reputation: 20463
I am trying plot Months with Year as subgroups to a chart with ggplot2. That is, something that looks like this:
A similar question was answered here, but I am hoping there is a better way that avoids hardcoding the axis labels.
The R code for the data frame is as follows:
set.seed(100)
df = data.frame( Year = rep(c(rep(2013, 12), rep(2014, 9)), 2)
, Month = rep(rep(month.abb, 2)[1:21], 2)
, Condition = rep(c("A", "B"), each=21)
, Value = runif(42))
As a bonus, I would appreciate learning how to plot smoothed totals by year without introducing a new variable (if this is possible?). If I use dplyr
to summarise
and group_by
Year and Month, the order of the months is not preserved.
Notice, Month now starts at Apr:
group_by(df, Year, Month) %>% summarise(total = sum(Value)) %>% head
Source: local data frame [6 x 3]
Groups: Year
Year Month total
1 2013 Apr 0.4764846
2 2013 Aug 0.9194172
3 2013 Dec 1.2308575
4 2013 Feb 0.7960212
5 2013 Jan 1.0185700
6 2013 Jul 1.6943562
Upvotes: 1
Views: 1319
Reputation: 77096
try this,
df$Month <- factor(df$Month, levels=month.abb)
p <- ggplot(df, aes(Month, Value, colour=Condition, group=Condition))+
facet_grid(.~Year) + geom_line() + theme_minimal()
library(gtable)
g <- ggplotGrob(p)
g2 <- g[-3,] %>%
gtable_add_rows(heights = g$heights[3], nrow(g)-3) %>%
gtable_add_grob(g[3,], t = nrow(g)-2, l=1, r=ncol(g))
grid.newpage()
grid.draw(g2)
Upvotes: 1