Search code examples
rggplot2facetannotate

Annotate each facet on a qplot separately, when using two variables to facet


I am producing a faceted graph with 4 facets, using two variables each with 2 levels to define facets.

I am using a code like this:

qplot(hp, mpg, data=mtcars, 
  facets=vs~am, size=I(3), geom=c("point","smooth"),
  xlab="Horsepower", ylab="Miles per Gallon")

I am trying to place a unique label onto each facet that says "Slope = the slope of the line"

I have seen a few questions on here that describe how to do this when facets are defiend by one variable, but not 2. How do I go about adding unique labels?

I know I can use geom_text, something like this

geom_text(sig=c("Slope = 1","Slope = 2","Slope = 3","Slope = 4")),aes(x=4.5,y=1,label=sig))

Solution

  • Try:

    mtcars$slope = with(mtcars, ifelse(am & vs, 1, ifelse(am,2, ifelse(vs, 3, 4))))
    
    ggplot(data=mtcars)+
        geom_point(aes(x=hp, y=mpg))+
        facet_grid(vs~am)+
        labs(x="Horsepower", y="Miles per gallon")+
        geom_text(aes(x=250,y=50,label=paste("slope=",slope)))
    

    enter image description here