Building on @Greg's answer, I believe it is is safer to recreate the factor levels in the aes
call in geom_rect
. This is because it is the factor levels rather than the character strings that are coerced to integer.
ggplot(mpg, aes(x=displ, y=manufacturer)) +
geom_point() +
geom_rect(aes(ymin = which(levels(as.factor(manufacturer))=="audi") -0.5,
ymax = which(levels(as.factor(manufacturer))=="audi") +0.5,
xmin=1.8,
xmax=3,
fill="red"))
This works even if the factor levels have been altered from default:
my.mpg <- mpg
my.mpg$manufacturer <-as.factor(my.mpg$manufacturer)
my.mpg$manufacturer <-factor(my.mpg$manufacturer,
levels = rev(levels(my.mpg$manufacturer)))
ggplot(my.mpg, aes(x=displ, y=manufacturer)) +
geom_point() +
geom_rect(aes(ymin = which(levels(as.factor(manufacturer))=="audi") -0.5,
ymax = which(levels(as.factor(manufacturer))=="audi") +0.5,
xmin=1.8,
xmax=3,
fill="red"))
In contrast, the which(unique(...))
method fails:
man_list <- unique(my.mpg$manufacturer)
ggplot(my.mpg, aes(x=displ, y=manufacturer)) +
geom_point() +
# geom_rect(aes(xmin=1.8, xmax=3.0, ymin= "audi", ymax=lead("audi"), fill='red'))
geom_rect(aes(ymin = which(man_list=="audi")-0.5,
ymax = which(man_list=="audi")+0.5,
xmin=1.8,
xmax=3,
fill="red"))