Plots in R with base graphics

Draw histograms, box plots, and scatter plots with a fitted line in base R, and label them properly for a paper. Runnable examples included.

About 12 minutes, every example runs in your browser

A statistic summarises; a plot testifies. Before you trust any test from the previous lessons, look at the data, and base R can draw everything you need with three functions: hist(), boxplot(), and plot(). The playground renders these right in your browser.

Histograms: the shape of one variable

The histogram answers the first question you should ask of any numeric variable: is it roughly symmetric, skewed, or lumpy?

hist(mtcars$mpg,
     main = "Fuel efficiency of 32 cars",
     xlab = "Miles per gallon",
     col  = "steelblue")

Every plot function takes main (title) and xlab/ylab (axis labels). Unlabelled axes are the fastest way to lose a reviewer's trust, so make labelling a reflex.

Box plots: groups side by side

The box shows the median and interquartile range; whiskers extend to the typical range and outliers appear as points. With the formula interface it becomes the natural companion to the t-test and ANOVA:

boxplot(weight ~ group, data = PlantGrowth,
        main = "Plant yield by condition",
        xlab = "Condition", ylab = "Dried weight (g)",
        col  = "lightsteelblue")

Compare this picture with the ANOVA from lesson 4: you can see trt2 sitting above trt1 before you compute a single p-value.

Scatter plots: two variables and a line

The scatter plot is regression's native picture. abline() overlays the fitted line from lm() onto it:

plot(mpg ~ wt, data = mtcars,
     main = "Heavier cars use more fuel",
     xlab = "Weight (1000 lbs)", ylab = "Miles per gallon",
     pch  = 19)
abline(lm(mpg ~ wt, data = mtcars), lwd = 2)

pch = 19 picks solid points and lwd = 2 thickens the line. Those two tweaks alone take a default R plot most of the way to figure quality.

A figure checklist for papers

  • Axis labels with units, always; a real title (or a numbered figure caption)
  • One message per figure: if you need to explain it for a minute, split it
  • Show the data when you can: points over bars, distributions over lone means
  • Label directly on the figure rather than relying on a legend when practical

You made it

Six lessons ago you had not typed a line of R. You can now load data, describe it, run t-tests, ANOVA, correlation, and regression, and draw the figures that back them up. Keep the playground open and rerun these examples with your own numbers; that is where it becomes yours.

Ready to turn your spreadsheet into results?

Create an account and run your first analysis in minutes. No install, no statistics course required.