将多个文本注释添加到多面ggplot geom_histogram

时间:2014-10-08 11:42:30

标签: r ggplot2

我有以下data.frame

hist.df <- data.frame(y = c(rnorm(30,1,1), rnorm(15), rnorm(30,0,1)), 
                      gt = c(rep("ht", 30), rep("hm", 15), rep("hm", 30)), 
                      group = c(rep("sc", 30), rep("am", 15), rep("sc",30)))

我从中生成以下刻面直方图ggplot

main.plot <- ggplot(data = hist.df, aes(x = y)) + 
  geom_histogram(alpha=0.5, position="identity", binwidth = 2.5, 
                 aes(fill = factor(gt))) + 
  facet_wrap(~group) + 
  scale_fill_manual(values = c("darkgreen","darkmagenta"), 
                    labels = c("ht","hm"), 
                    name = "gt",
                    limits=c(0, 30))

enter image description here

另外,我有data.frame

text.df = data.frame(ci.lo = c(0.001,0.005,-10.1), 
                     ci.hi = c(1.85,2.25,9.1), 
                     group = c("am","sc","sc"), 
                     factor = c("nu","nu","alpha"))

它定义了我想要添加到分面直方图的文本注释,以便最终的数字是:

enter image description here

所以text.df$ci.lotext.df$ci.hi是相应text.df$factor的置信区间,它们通过text.df $ group

对应于分面直方图

请注意,并非每个直方图都包含text.df$factor

理想情况下,分面直方图的ylim将为直方图上方的文本留下足够的空间,使它们只出现在背景上。

知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

将我的评论包含在答案中:

text.df$ci <- paste0(text.df$factor, ' = [', text.df$ci.lo, ', ', text.df$ci.hi, ']')
new_labels <- aggregate(text.df$ci, by = list(text.df$group), 
                        FUN = function(x) paste(x, collapse = '\n'))$x
hist.df$group <- factor(hist.df$group)
hist.df$group <- factor(hist.df$group,
                        labels = paste0(levels(hist.df$group), '\n', new_labels))

main.plot <- ggplot(data = hist.df, aes(x = y)) + 
  geom_histogram(alpha=0.5, position="identity", binwidth = 2.5, 
                 aes(fill = factor(gt))) + 
  facet_wrap(~group) + 
  scale_fill_manual(values = c("darkgreen","darkmagenta"), 
                    labels = c("ht","hm"), 
                    name = "gt")
main.plot + theme(strip.text = element_text(size=20))

enter image description here

如果您希望坚持最初的想法,this question会有一个有用的答案。