2

I have the following 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)))

from which I produce the following faceted histogram 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

In addition, I have this 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"))

Which defines the text annotations I want to add to the faceted histograms, so that the final figure will be:

enter image description here

So text.df$ci.lo and text.df$ci.hi are confidence intervals on the corresponding text.df$factor and they correspond to the faceted histograms through text.df$group

Note that not every histogram has all text.df$factor's.

Ideally, the ylim's of the faceted histograms will leave enough space for the text to be added above the histograms so that they appear only on the background.

Any idea how to achieve this?

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
user1701545
  • 5,706
  • 14
  • 49
  • 80
  • You may consider an option of adding this annotation to the header, e.g. `sc` will be something along the lines of `paste('sc', 'nu=[]', 'alpha=[]', sep='\n')`. That will be consistent across facets and won't overlap the histogram. – tonytonov Oct 08 '14 at 11:55
  • Thanks a lot. But I still prefer to have it as text annotation since it makes the header too bulky. – user1701545 Oct 08 '14 at 14:04

1 Answers1

2

Wrapping my comment into an answer:

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

If you wish to stick to the original idea, this question has an answer that will help.

Community
  • 1
  • 1
tonytonov
  • 25,060
  • 16
  • 82
  • 98