1

Using ggplot2 I have made facetted histograms using the following code.

library(ggplot2)
library(plyr)

df1 <- data.frame(monthNo = rep(month.abb[1:5],20),
classifier = c(rep("a",50),rep("b",50)),
    values = c(seq(1,10,length.out=50),seq(11,20,length.out=50))
    )

means <- ddply (df1,
    c(.(monthNo),.(classifier)),
    summarize,
    Mean=mean(values)
    )


ggplot(df1,
aes(x=values, colour=as.factor(classifier))) +
geom_histogram() +
facet_wrap(~monthNo,ncol=1) +
geom_vline(data=means, aes(xintercept=Mean, colour=as.factor(classifier)),
           linetype="dashed", size=1) 

The vertical line showing means per month is to stay.

But I want to also add text over these vertical lines displaying the mean values for each month. These means are from the 'means' data frame.

I have looked at geom_text and I can add text to plots. But it appears my circumstance is a little different and not so easy. It's a lot simpler to add text in some cases where you just add values of the plotted data points. But cases like this when you want to add the mean and not the value of the histograms I just can't find the solution.

Please help. Thanks.

G5W
  • 36,531
  • 10
  • 47
  • 80
jc52766
  • 61
  • 4
  • possible duplicate of [ggplot2: geom\_text() with facet\_grid()?](http://stackoverflow.com/questions/15867263/ggplot2-geom-text-with-facet-grid) – hrbrmstr Oct 27 '14 at 01:26
  • I felt that it was different to http://stackoverflow.com/questions/15867263/ggplot2-geom-text-with-facet-grid for the reason that I want the mean value to sit on top of the mean vlines. Therefore I need a way to change the x coordinates depending on the mean value of the text I want to add to the plot. – jc52766 Oct 27 '14 at 01:38
  • possible duplicate of [Annotating text on individual facet in ggplot2](http://stackoverflow.com/questions/11889625/annotating-text-on-individual-facet-in-ggplot2) – user20650 Oct 27 '14 at 01:45

1 Answers1

3

Having noted the possible duplicate (another answer of mine), the solution here might not be as (initially/intuitively) obvious. You can do what you need if you split the geom_text call into two (for each classifier):

ggplot(df1, aes(x=values, fill=as.factor(classifier))) +
  geom_histogram() +
  facet_wrap(~monthNo, ncol=1) +
  geom_vline(data=means, aes(xintercept=Mean, colour=as.factor(classifier)),
             linetype="dashed", size=1) +
  geom_text(y=0.5, aes(x=Mean, label=Mean),
            data=means[means$classifier=="a",]) +
  geom_text(y=0.5, aes(x=Mean, label=Mean),
            data=means[means$classifier=="b",]) 

enter image description here

I'm assuming you can format the numbers to the appropriate precision and place them on the y-axis where you need to with this code.

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205