Contents

Acknowledgements

This is a slightly modified version of Martin Morgan’s original vignette.

1 Colors

Colors should reflect the nature of the data and be carefully chosen to convey equivalent information to all viewers. The RColorBrewer package provides an easy way to choose colors; see also the colorbrewer2 web site.

library(RColorBrewer)
display.brewer.all()

We’ll use a color scheme from the ‘qualitative’ series, to represent different levels of factors and for choice of colors. We’ll get the first four colors.

palette <- brewer.pal(4, "Dark2")

2 Quick overview of ‘Base’ Graphics

We’ll illustrate ‘base’ graphics using the built-in mtcars data set

data(mtcars)     # load the data set
head(mtcars)     # show header and top 6 lines
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

The basic model is to plot data, e.g., the relationshiop between miles per gallon and horsepower. The relationship is symbolized by ~.

plot(mpg ~ hp, mtcars)
Plotting example. Within the default plot each point is represented by an open circle.

Figure 1: Plotting example
Within the default plot each point is represented by an open circle.

The appearance can be influenced by arguments, see ?plot then ?plot.default and par.

For example, the code below is modified to change to a green filled circle, larger than the default size.

plot(mpg ~ hp, mtcars, pch=20, cex=2, col=palette[1])
Modified plot example.

Figure 2: Modified plot example

More complicated plots can be composed via a series of commands, e.g., to plot a linear regression: we first make the plot, and then add the regression line using abline().

The line is first computer with the lm() linear model function.

We can also define the line width (lwd) and its color (col.)

# Make the default plot
plot(mpg ~ hp, mtcars)
# Compute regression line
fit <- lm(mpg ~ hp, mtcars)
# Add line to the plot
abline(fit, col=palette[1], lwd=3)