Use of facet_wrap function of ggplot2 package in R

r
datavisualization
ggplot2

#1

Hi,

I was learning about ggplot2 package in R and I came across the function facet_wrap. I am not able to understand what it does and how to implement it. I have used qplot and facet_grid

qplot(displ, hwy, data=mpg, colour=class)+ facet_grid(.~cyl)

the help viwer gives an example like

p <- qplot(price, data = diamonds, geom = “histogram”, binwidth = 1000)
p + facet_wrap(~ color)

I tried the same on my data->

p<-qplot(displ, hwy, data=mpg, colour=class)
p+facet_wrap(~ color)

but I am getting an error saying->
Error in layout_base(data, vars, drop = drop) :
At least one layer must contain all variables used for facetting

How to use facet_wrap and what does it do?

Thank you.


#2

hello @Aditya_Sharma,

Taking your example of the qplot on mpg dataset in R:

> qplot(displ, hwy, data=mpg)

Now if I want to display the result for every class in the dataset:

p<-qplot(displ, hwy, data=mpg);p+facet_wrap(~class)

Notice how the graphs have been generated for each class in the data.
Hope this helps!!


#3

can anyone of you explain why this is not working :slight_smile:

> qplot(displ, hwy, data=mpg)+facet_wrap(class~)

Thanks in advance


#4

Hi @vijaypalmanit,

There’s ;p before facet_wrap


#5

No thats not the issue, that code is working fine, problem is that why this is working :slight_smile:

qplot(displ, hwy, data=mpg)+facet_wrap(~class)

but not this :

qplot(displ, hwy, data=mpg)+facet_wrap(class~)

I mean why I am not able to facet wrap by row ?


#6

Ok. I’m sorry but somebody else may be able to help.


#7

Instead of facet_wrap, you can try facet_grid:
Note the difference in syntax. It needs a dot.

facet_grid(class~.)
OR
facet_grid(.~class)