I learnt how to put vertical and horizontal lines on a facetted plot from here. Now I wanted to modify the code so that I could pass the xintercept
and yintercept
using a variable, however, I don't think I am using aes
or aes_
correctly.
First, let us replicate the original example (with slightly different intercepts:
# set up data
library(ggplot2)
tmp_intercepts <- data.frame(x = c(5, 3, 1))
iris$species_num <- as.numeric(iris$Species)
p <-
ggplot(iris, aes(Sepal.Length, Petal.Length)) + facet_wrap(~Species, scales="free") + geom_point()
## original plot works fine
for (i in 1:3) {
if (i == 1) {
p_orig <-
p +
geom_vline(data=filter(iris, species_num == i), aes(xintercept=5), colour="pink")
} else if (i == 2) {
p_orig <-
p_orig +
geom_vline(data=filter(iris, species_num == i), aes(xintercept=3), colour="blue")
} else {
p_orig <-
p_orig +
geom_hline(data=filter(iris, species_num == i), aes(yintercept=1), colour="green")
}
}
I will now make two plots, one using a loop with aes
, and the other using aes_
. Both fail to reproduce the first plot (Look at the location of the vertical lines).
## but once you try to pass in a variable it fails
for (i in 1:3) {
if (i == 1) {
p_loop <-
p +
geom_vline(data=filter(iris, species_num == i), aes(xintercept=tmp_intercepts$x[i]), colour="pink")
} else if (i == 2) {
p_loop <-
p_loop +
geom_vline(data=filter(iris, species_num == i), aes(xintercept=tmp_intercepts$x[i]), colour="blue")
} else {
p_loop <-
p_loop +
geom_hline(data=filter(iris, species_num == i), aes(yintercept=tmp_intercepts$x[i]), colour="green")
}
}
## if you do it one by one it is not fine either!
tmp_x <- 5
p_obo <-
p +
geom_vline(data=filter(iris, species_num == 1), aes_(xintercept=quote(tmp_x)), colour="pink")
tmp_x <- 3
p_obo <-
p_obo +
geom_vline(data=filter(iris, species_num == 2), aes_(xintercept=quote(tmp_x)), colour="blue")
tmp_x <- 1
p_obo <-
p_obo +
geom_hline(data=filter(iris, species_num == 3), aes_(yintercept=quote(tmp_x)), colour="green")
Plotting so that the original is at the top via plot(gridExtra::arrangeGrob(p_orig, p_loop, p_obo, ncol = 1))
:
I think I am using aes
incorrectly.