制作智能多级直方图

时间:2015-01-03 11:28:10

标签: r ggplot2 histogram

我在Windows上使用RStudio版本0.98.1028。 我想使用ggplot2制作多级直方图。我们假设我有一个像这样的4D数据框:

facet <- as.factor(rep(c('alpha', 'beta', 'gamma'), each = 4, times = 3))
group <- as.factor(rep(c('X', 'Y'), each = 2, times = 9))
type <- as.factor(rep(c('a', 'b'), each = 1, times = 18))
day <- as.factor(rep(1:3, each = 12)

df = data.frame(facet = facet, group = group, type = type, day = day, value = abs(rnorm(36)))

我希望在3个方面制作x = day vs y = value的直方图,对应facet,按group分组并填充{{1} }。换句话说,我想将typea堆积在一个条形图中,但为bX分隔条形图。它看起来像

Y

不幸的是,使用g = ggplot(df, aes(day, value, group = group, fill = type)) g + geom_histogram(stat = 'identity', position = 'dodge') + facet_grid(facet ~ .) 选项,我获得了未被堆叠的直方图,而没有我每天获得4个条形图。关于如何解决这个问题的任何想法?

使用excel一个facet看起来应该是这样的

enter image description here

提前致谢!

EB

3 个答案:

答案 0 :(得分:1)

好吧,也许你的问题与this one on the ggplot group有关。 可能的解决方案如下:

g = ggplot(df, aes(group, value, fill = type))
g + geom_bar(stat = 'identity', position = 'stack') +
    facet_grid(facet ~ day)

它不是最理想的,因为你使用了两个方面,但是通过这种方式你得到了这个数字: enter image description here

答案 1 :(得分:1)

正如@Matteo指出的那样,ggplot2提供的工具可能无法直接实现您的具体愿望。下面提供的一点点黑客攻击可能指向正确的方向 - 我并不赞同它太多但是我只花了几分钟玩,围绕着它。也许你可以选择一些元素。

我将group and day合并为一个因子,当绘图时,使用(非唯一)组名称手动替换x标签。然后,我(以懒惰的方式)包括日标签。我仍然觉得天x面是你应该继续的方式。

df$combinedCategory <- as.factor(paste(df$day,df$group))
library(scales)
g = ggplot(df, aes(combinedCategory, value, fill = type))
g = g + geom_bar(stat='identity',position = 'fill')
g = g +   facet_grid(facet ~ .)
g = g + scale_y_continuous(labels  = percent)
g = g + scale_x_discrete(labels = c("X","Y"))
g = g + geom_text(aes(x=1.5,y=0.05, label="Day 1"))
g = g + geom_text(aes(x=3.5,y=0.05, label="Day 2"))
g = g + geom_text(aes(x=5.5,y=0.05, label="Day 3"))
g = g + theme_minimal()
g

这给出了以下内容:

enter image description here

答案 2 :(得分:0)

确实在y = interaction(group, day)中设置aes()就足够了。这实际上是我的第一步,但我想知道是否存在更精确的东西。显然不是:这里唯一棘手的问题是创建一个二级x轴标签行。谢谢大家!