2014-10-08 58 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有一個答案,這將有助於。