I am doing some analysis in ggplot2 at the moment for a project and by chance I stumbled across some (for me) weird behavior that I cannot explain. When I write aes(x = cyl, ...)
the plot looks different to what it does if I pass the same variable using aes(x = mtcars$cyl, ...)
. When I remove facet_grid(am ~ .)
both graphs are the same again. The code below is modeled after the code in my project that generates the same behavior:
library(dplyr)
library(ggplot2)
data = mtcars
test.data = data %>%
select(-hp)
ggplot(test.data, aes(x = test.data$cyl, y = mpg)) +
geom_point() +
facet_grid(am ~ .) +
labs(title="graph 1 - dollar sign notation")
ggplot(test.data, aes(x = cyl, y = mpg)) +
geom_point()+
facet_grid(am ~ .) +
labs(title="graph 2 - no dollar sign notation")
Here is the picture of graph 1:
Here is the picture of graph 2:
I found that I can work around this problem using aes_string
instead of aes
and passing the variable names as strings, but I would like to understand why ggplot is behaving that way. The problem also occurs in similar attempts with facet_wrap
.