2014-10-08 87 views
2

我有以下data.frame添加多个文本注释的方位ggplot geom_histogram

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 $组

请注意,并非每个直方图都具有所有text.df$factor的s。

理想情况下,多面直方图的ylim将留出足够的空间,以便将文字添加到直方图上方,以便它们仅出现在背景上。

任何想法如何实现这一目标?

+0

您可以考虑将此注释添加到标题的选项,例如, 'sc'将沿着'paste'('sc','nu = [''','alpha = [''',sep ='\ n')'行。这将在各个方面保持一致,并且不会与直方图重叠。 – tonytonov 2014-10-08 11:55:10

+0

非常感谢。但我仍然希望将它作为文本注释,因为它会使标题太庞大。 – user1701545 2014-10-08 14:04:30

回答

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有一个答案,这将有助于。