How to Simplify Results (or Not) with the sapply Function in R
How to Find Help Using R Mailing Lists
How to Change Plot Options in R

How to Print and Save a Lattice Plot in R

You need to know three essential things about lattice plots in R: how to assign a lattice plot to an object, how to print a lattice plot in a script, and how to save a lattice plot to file.

How to assign a lattice plot to an object in R

Lattice plots are objects; therefore you can assign them to variables, just like any other object. This is very convenient when you want to reuse a plot object in your downstream code — for example, to print it later.

The assignment to a variable works just like any variable assignment in R:

> my.plot <- xyplot(mpg ~ hp | cyl, data=mtcars)
> class(my.plot)
[1] "trellis"

How to print a lattice plot in an R script

When you run code interactively — by typing commands into the R console — simply typing the name of a variable prints that variable. However, you need to explicitly print an object when running a script. You do this with the print() function.

Because a lattice plot is an object, you need to explicitly use the print() function in your scripts. This is a frequently asked question in the R documentation, and it can easily lead to confusion if you forget.

To be clear, the following line of code will do nothing if you put it in a script and source the script. (To be technically correct: the code will still run, but the resulting object will never get printed — it simply gets discarded.)

> xyplot(mpg ~ hp | cyl, data=mtcars)

To get the desired effect of printing the plot, you must use print():

> my.plot <- xyplot(mpg ~ hp | cyl, data=mtcars)
> print(my.plot)

How to save a lattice plot to file

To save a lattice plot to an image file, you use a slightly modified version of the sequence of functions that you came across in base graphics.

Here’s a short reminder of the sequence:

  1. Open a graphics device using, for example, png().

    The lattice package provides the trellis.device() function that effectively does the same thing, but it’s optimized for lattice plots, because it uses appropriate graphical parameters.

  2. Print the plot.

    You must use the print() function explicitly!

  3. Close the graphics device.

Put this into action using trellis.device() to open a file called xyplot.png, print your plot, and then close the device. You can use the setwd("~/") to set your working directory to your home folder.

> setwd("~/")
> trellis.device(device="png", filename="xyplot.png")
> print(my.plot)

You should now be able to find the file xyplot.png in your home folder.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
R Code Editor Options
Base, Grid, and Lattice Graphics in R
How to Unload CRAN Packages in R
How to Concatenate Text Cases in R
How to Test Data Normality in a Formal Way in R