Annotating group means on each facet in ggplot2

I want to anotate mean values for each facet group in a ggplot2 graphic. I´ve tried this:

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = mean(as.numeric(mtcars$mpg)), size = 4, x = 15, y = 5)
p

enter image description here

Following the example of another quiestion, i achieved label the mean on each facet, but now i get tree empty grids extra: library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(cols=vars(cyl))
ann_text <- data.frame(mpg = c(15, 15, 15),
                       wt = c(5,5,5),
                       lab = c(mean(as.numeric(mtcars$mpg[mtcars$cyl==4])),
                               mean(as.numeric(mtcars$mpg[mtcars$cyl==6])),
                               mean(as.numeric(mtcars$mpg[mtcars$cyl==8]))),
                       cyl =  c("4","6","8"))
p <- p + geom_text(data=ann_text, label=ann_text$lab)
p

enter image description here

Upvotes: 2

Views: 1630

Answers (1)

Antonios
Antonios

Reputation: 1939

One way it could work is to create a new col with the labels in the original df:

mtcars0=mtcars%>%group_by(cyl)%>%mutate(MeanMpg=round(mean(mpg),2))

p <- ggplot(mtcars0, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl) + 
  geom_text(aes(mpg,wt,label=MeanMpg), size = 4, x = 15, y = 5)
p

if you want to use annotate, it could be done by defining labels separately:

labels<-mtcars%>%group_by(cyl)%>%summarize(MeanMpg=round(mean(mpg),2))%>%.$MeanMpg

p <- ggplot(mtcars0, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl) +                                                            
  annotate("text", label = labels, size = 4, x = 15, y = 5)
p 

Upvotes: 1

Related Questions