I am trying to plot some data from my experiment in R using ggplot2
, and I am trying to split the graph in two parts using facet_grid()
.
Here is an MWE I built with the cars dataset:
data(mtcars)
ggplot(data=mtcars, aes(x=mtcars$mpg,y=mtcars$cyl)) +
geom_point()+
facet_grid(rows=mtcars$disp)
I get the following error:
Error in facet_grid(rows = mtcars$disp) :
unused argument (rows = mtcars$disp)
I really have no idea why this is happening. I used this function before, and it worked fine. Would appreciate ideas on how to solve this.
edit: I accepted the second answer, because it provides some more context, but as I see it, both are equally correct in pointing out that I need to quote the variable name. The actual error was resolved after installig R and all packages again. Now I have a new error, but that is another story. Thanks again!
First, don't explicitly refer to mtcars
within the aes()
call.
Second, quote the facet argument.
library(ggplot2)
ggplot(data=mtcars, aes(x=mpg,y=cyl)) +
geom_point()+
facet_grid(rows="disp")
Also, consider creating a new variable that collapses disp
into fewer values for the facet to be more meaningful & readable.
Here's an example of four arbitrary cut points.
mtcars$disp_cut_4 <- cut(mtcars$disp, breaks=c(0, 200, 300, 400, 500))
ggplot(data=mtcars, aes(x=mpg,y=cyl)) +
geom_point()+
facet_grid(rows="disp_cut_4")