子组轴ggplot2类似于Excel PivotChart [英] Subgroup axes ggplot2 similar to Excel PivotChart
问题描述
我正在尝试使用年份的月份作为具有ggplot2的图表的子组。那就是这样的东西:
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.
数据帧的R代码如下:
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))
作为一个奖励,我会很乐意学习如何绘制平滑的总计,而不引入一个新的变量(如果这是可能的话)。如果我使用 dplyr
到总结
和 group_by
年和月这个月份的顺序不会被保留。
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.
注意,现在从4月开始:
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
推荐答案
p>尝试这个,
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)
这篇关于子组轴ggplot2类似于Excel PivotChart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!