R Plot
R's built-in base graphics can draw a chart with a single function call. The most general one is plot(). In the playground, every chart your code draws appears as an image under the text output.
x <- 1:8
y <- c(3, 5, 4, 7, 9, 8, 11, 12)
plot(x, y)
cat("Plotted", length(x), "points\n")Plotted 8 points
Given two numeric vectors, plot() draws a scatter plot: one point per pair of values, with x on the horizontal axis and y on the vertical axis. Axis labels default to the variable names.
A single vector
With only one vector, R plots the values against their position (the index):
water_ml <- c(250, 400, 300, 500, 450, 200, 350)
plot(water_ml)
summary(water_ml) Min. 1st Qu. Median Mean 3rd Qu. Max.
200 275 350 350 425 500
Titles and labels
The most common arguments work in almost every plotting function:
| Argument | Meaning |
|---|---|
main |
title above the plot |
xlab, ylab |
axis labels |
xlim, ylim |
axis ranges, e.g. ylim = c(0, 100) |
col |
colour (name such as "tomato", or hex "#276dc3") |
pch |
point symbol (0–25; 19 = solid circle) |
cex |
size multiplier for points/text |
type |
"p" points, "l" lines, "b" both, "h" vertical bars, "n" nothing |
hours <- c(1, 2, 3, 4, 5, 6)
score <- c(52, 58, 66, 70, 79, 85)
plot(hours, score,
main = "Study time vs. exam score",
xlab = "Hours studied", ylab = "Score (%)",
col = "#276dc3", pch = 19, cex = 1.5,
ylim = c(40, 100))
data.frame(hours, score) hours score
1 1 52
2 2 58
3 3 66
4 4 70
5 5 79
6 6 85
Plot types
The type argument changes how the same data is drawn. par(mfrow = c(rows, cols)) splits the drawing area so several plots appear side by side:
y <- c(2, 4, 3, 6, 5, 8)
par(mfrow = c(1, 3))
plot(y, type = "p", main = "points")
plot(y, type = "l", main = "lines")
plot(y, type = "b", main = "both")
cat("Three panels of", length(y), "values\n")Three panels of 6 values
Plotting a function
curve() draws a mathematical expression in x over a range:
curve(sin(x), from = 0, to = 2 * pi, col = "darkgreen", lwd = 2,
main = "One period of sin(x)")
abline(h = 0, lty = 2) # dashed horizontal line at y = 0
round(sin(c(0, pi / 2, pi, 3 * pi / 2)), 3)[1] 0 1 0 -1
Adding to an existing plot
Base graphics work like painting on a canvas: a high-level function (plot, hist, barplot) starts a new chart, and low-level functions add to it:
| Function | Adds |
|---|---|
points(x, y) |
more points |
lines(x, y) |
connected lines |
abline(a, b) / abline(h = , v = ) |
a straight line |
text(x, y, labels) |
text at coordinates |
legend(...) |
a legend |
title(), axis(), grid() |
titles, axes, grid lines |
We'll use these in the next lessons.
Test yourself
What does plot(c(5, 3, 8)) put on the x-axis?
- The values
- The index (1, 2, 3)
- Nothing
- The names
Which argument sets the plot title?
- title
- main
- label
- header
Which type draws both points and connecting lines?
- "p"
- "l"
- "b"
- "n"