geom_text writing all data on all facets

facet, ggplot2, overwrite, r

Solution

You almost have it. It is just that you need one more column in your `ldata` data frame which is what you will give to `facet_grid`. (I changed the Ypos to Inf)

Notice the role of the `splitter` column in `ldata` below, and how it is used in `facet_grid`

xpos <- c(10,10,10) 
ypos <- c(Inf,Inf,Inf)
lab <- c(378,2,50)
splitter <- c(1:3)
ldata <- data.frame(xpos, ypos, lab, splitter)


ggplot(mtcars) + geom_bar(aes(x=cyl)) + facet_grid(~splitter) + 
  geom_text(data=ldata, aes(x=xpos, y=ypos, 
                            label=lab, size=1), 
            vjust=2, parse=FALSE)

Which produces:

Problem

I used ggplot with facet_grid and I'd like to indicate on each facet the number of observations in each facet. I follow examples provided on many sites but when I get it to write anything, it writes all four observation numbers on top of each other on all four plots. Here the geom_text layer command: geom_text(data=ldata, aes(x=xpos, y=ypos, label=lab, size=1), group=NULL, hjust=0, parse=FALSE) and ldata is a data frame listing the coordinates (xpos, ypos) on each plot and the number of observations (lab). It's printing the numbers in the right position on the plot, but all four are written on top of each other on all four plots. I can not figure out what I'm doing wrong. ldata: xpos ypos lab 1 10 1.35 378 2 10 1.35 2 3 10 1.35 50 4 10 1.35 26

Original source