Plotting System

The core plotting and graphics engine in R is encapsulated in the following packages:

The lattice plotting system is implemented using the following packages:


The Process of Making a Plot

When making a plot one must first make a few considerations (not necessarily in this order):


The Process of Making a Plot

We focus on using the base plotting system to create graphics on the screen device.


Base Graphics

Base graphics are used most commonly and are a very powerful system for creating 2-D graphics.


Simple Base Graphics: Histogram

library(datasets)
hist(airquality$Ozone)  ## Draw a new plot


Simple Base Graphics: Scatterplot

library(datasets)
with(airquality, plot(Wind, Ozone))


Simple Base Graphics: Boxplot

library(datasets)
airquality <- transform(airquality, Month = factor(Month))
boxplot(Ozone ~ Month, airquality, xlab = "Month", ylab = "Ozone (ppb)")

Some Important Base Graphics Parameters

Many base plotting functions share a set of parameters. Here are a few key ones:


Some Important Base Graphics Parameters

The par() function is used to specify global graphics parameters that affect all plots in an R session. These parameters can be overridden when specified as arguments to specific plotting functions.


Some Important Base Graphics Parameters

Default values for global graphics parameters

par("lty")
## [1] "solid"
par("col")
## [1] "black"
par("pch")
## [1] 1

Some Important Base Graphics Parameters

Default values for global graphics parameters

par("bg")
## [1] "white"
par("mar")
## [1] 5.1 4.1 4.1 2.1
par("mfrow")
## [1] 1 1

Base Plotting Functions


Base Plot with Annotation

library(datasets)
with(airquality, plot(Wind, Ozone))
title(main = "Ozone and Wind in New York City")  ## Add a title


Base Plot with Annotation

with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City"))
with(subset(airquality, Month == 5), points(Wind, Ozone, col = "blue"))


Base Plot with Annotation

with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City", type = "n"))
with(subset(airquality, Month == 5), points(Wind, Ozone, col = "blue"))
with(subset(airquality, Month != 5), points(Wind, Ozone, col = "red"))
legend("topright", pch = 1, col = c("blue", "red"), legend = c("May", "Other Months"))


Base Plot with Regression Line

with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City", pch = 20))
model <- lm(Ozone ~ Wind, airquality)
abline(model, lwd = 2)


Multiple Base Plots

par(mfrow = c(1, 2))
with(airquality, {
    plot(Wind, Ozone, main = "Ozone and Wind")
    plot(Solar.R, Ozone, main = "Ozone and Solar Radiation")
})


Multiple Base Plots

par(mfrow = c(1, 3), mar = c(4, 4, 2, 1), oma = c(0, 0, 2, 0))
with(airquality, {
    plot(Wind, Ozone, main = "Ozone and Wind")
    plot(Solar.R, Ozone, main = "Ozone and Solar Radiation")
    plot(Temp, Ozone, main = "Ozone and Temperature")
    mtext("Ozone and Weather in New York City", outer = TRUE)
})


Summary