Using Faceting in ggplot2 to create Trellis-like Plots

November 9, 2009
By

(This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers)

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

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

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 his blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , , ,

Comments are closed.