Site icon R-bloggers

Using Faceting in ggplot2 to create Trellis-like Plots

[This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

One of the main strengths of the Trellis graphics paradigm is the use of panelling to divide data into subsets to investigate whether patterns are consistent as the conditioning variables change. In the ggplot2 package the terminology for specifying these separate panels is faceting and can be used to create similar displays.

In our previous post we consider creating a scatter plot for the data in R relating to the growth of Orange trees. If we wanted to create separate panels (graphs) for each of the trees we use the facets argument with the code below:

qplot(age, circumference, data = Orange, facets = . ~ Tree)

This will produce a graph like this:

Scatterplot Facet Example for Orange Tree data

The downside with this graph is that the individual panels are stretched vertically which may distort the interpretation of the graph. We can add the facet aspect to the graph object created by the qplot function using code such as:

qplot(age, circumference, data = Orange) + facet_wrap(~ Tree)

The facet_wrap function takes a single variable for conditioning and places the panels on multiple lines, which in this example will lead to a more appealing display:

Scatter plot with Panels on Multiple lines

This only scratches the surface of the power of faceting in the ggplot2 library. There are many options that can be controlled to change the appearance to suit a specific set of data.

To leave a comment for the author, please follow the link and comment on their blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.