1

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!

Maxim Moloshenko
  • 336
  • 3
  • 17

2 Answers2

2

This should do:

ggplot(data=mtcars, aes(mpg, cyl)) + 
 geom_point()+
 facet_grid(rows = "disp")

alternatively:

ggplot(data=mtcars, aes(mpg, cyl)) + 
 geom_point()+
 facet_grid(~disp)
JVP
  • 309
  • 1
  • 11
2

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.

not-cut

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")

cut

wibeasley
  • 5,000
  • 3
  • 34
  • 62
  • Thanks! I didn't know about the quotes! I tried your suggestion, but it didn't work. I guess something is wrong with my installation? I will try to update everything, and will post an update soon. – Maxim Moloshenko Dec 21 '18 at 17:11