This lesson is being piloted (Beta version)

Basic plotting with R

Overview

Teaching: 30 min
Exercises: 0 min
Questions
  • How to plot in R

Objectives
  • Learn using plotting tool in R

  • Learn to export graphical to file

Course content:

Exploratory graph

Why do we use graphs in data analysis?

Ploting System

There are 3 main plotting systems in R:

The Base plotting system

- Start with blank plot and build up the plot
- Plot is just a series of R command
- Flexible

The Lattice plotting system (using package::lattice)

- Plots created using single function call
- Good for putting many plots to screen
- Cannot add to plots once created

The ggplot plotting system (using package::ggplot2)

- Similar to Lattice but easier
- Many default mode
- Flexible between Base and Lattice

The Base plotting system

Important BASE graphic parameters

pch: the plotting symbol (default is open circle)
lty: the line type (default is solid line), can be dashed, dotted, etc.
lwd: the line width, specified as an integer multiple
col: the plotting color, specified as a number, string, or hex code; the colors() function gives you a vector of colors by name
xlab: character string for the x-axis label
ylab: character string for the y-axis label

Important BASE plotting function

plot: make a scatterplot, or other type of plot depending on the class of the object being plotted
lines: add lines to a plot, given a vector x values and a corresponding vector of y values (or a 2-column matrix); this function just connects the dots
points: add points to a plot
text: add text labels to a plot using specified x, y coordinates
title: add annotations to x, y axis labels, title, subtitle, outer margin
mtext: add arbitrary text to the margins (inner or outer) of the plot
axis: adding axis ticks/labels

Motor Trend Car Road Tests example

The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).

Graphics Devices

A graphics device is something where you can make a plot appear When you make a plot in R, it has to be “sent” to a specific graphics device.

The most common place for a plot to be “sent” is the screen device

dev.copy(png,"filename.png") # to save the image to file
dev.off() # to close all the graphical devices

Key Points

  • Plot