1

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))
Kev
  • 118,037
  • 53
  • 300
  • 385
Shannon Hodges
  • 163
  • 1
  • 6

2 Answers2

2

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

rnso
  • 23,686
  • 25
  • 112
  • 234
0

I also found a method outlied here that allows you to change where one of the labels is placed. Ie not all labes have to be at the same x,y co-ordinates.

mtcars[, c("cyl", "am", "gear")] <- lapply(mtcars[, c("cyl", "am", "gear")], as.factor)

attach(mtcars)

p <- qplot (hp, mpg, facets=vs~am, size=I(3), xlab="hp", ylab="mpg")

len <- length(levels(mtcars$vs)) *  length(levels(mtcars$am))
vars <- data.frame(expand.grid(levels(mtcars$vs), levels(mtcars$am)))
colnames(vars) <- c("vs", "am")
dat <- data.frame(x = 300, y = 50, vars, labs=LETTERS[1:len])

p <- p + geom_text(aes(x, y,
    label=c("Slope = 1","Slope = 2","Slope = 3","Slope = 4"),
    group=NULL), data=dat)

p

To change the location of one specific label:

dat[1, 1:2] <- c(200, 20)   #to change specific locations
p
Shannon Hodges
  • 163
  • 1
  • 6