jc52766
jc52766

Reputation: 61

Adding text to facetted histogram

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.

Upvotes: 1

Views: 1743

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78832

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.

Upvotes: 3

Related Questions