2

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

  • The way to annotate different values on each facet is to first make a dataframe with a mean for each facet variable, and then annotate values from the dataframe. See [this question](https://stackoverflow.com/questions/11889625/annotating-text-on-individual-facet-in-ggplot2) for examples. – Jan Boyer Jan 16 '19 at 17:52
  • In that exemple i did'nt Understand Howthat could apply for my case. They put only one text in one of the facets – Armando González Díaz Jan 16 '19 at 18:10
  • scroll down - the first answer only annotates one facet with text, but one of the answers further down shows how to annotate each facet with different text values. – Jan Boyer Jan 16 '19 at 18:44

1 Answers1

1

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 
Antonios
  • 1,919
  • 1
  • 11
  • 18