TExcelTAD
Home › R › R Line

R Line

A line graph shows how a value changes over an ordered variable, usually time. In R you get one by adding type = "l" to plot().

r · try it yourself
months <- 1:12
rainfall <- c(78, 61, 55, 44, 50, 38, 21, 25, 47, 82, 95, 88)
plot(months, rainfall, type = "l",
     main = "Monthly rainfall", xlab = "Month", ylab = "mm")
cat("Wettest month:", which.max(rainfall), "with", max(rainfall), "mm\n")
Wettest month: 11 with 95 mm

Line colour, width and style

Argument Meaning Values
col colour "red", "#276dc3", …
lwd line width 1 (default), 2, 3, …
lty line type 1 solid, 2 dashed, 3 dotted, 4 dot-dash, 5 long dash, 6 two-dash
r · try it yourself
x <- 1:10
plot(x, x^1.5, type = "l", col = "tomato", lwd = 3, lty = 2,
     main = "A thick dashed line", ylab = "x^1.5")
round(x^1.5, 1)
 [1]  1.0  2.8  5.2  8.0 11.2 14.7 18.5 22.6 27.0 31.6

Several lines in one chart

Draw the first line with plot(), then add more with lines(). Set ylim in the first call so every line fits:

r · try it yourself
year <- 2018:2024
north <- c(120, 135, 128, 150, 162, 170, 185)
south <- c(100, 98, 115, 120, 118, 140, 152)
plot(year, north, type = "l", col = "steelblue", lwd = 2,
     ylim = range(north, south), main = "Sales by region", ylab = "Units")
lines(year, south, col = "darkorange", lwd = 2, lty = 2)
legend("topleft", legend = c("North", "South"),
       col = c("steelblue", "darkorange"), lwd = 2, lty = c(1, 2))
data.frame(year, north, south)
  year north south
1 2018   120   100
2 2019   135    98
3 2020   128   115
4 2021   150   120
5 2022   162   118
6 2023   170   140
7 2024   185   152

legend() takes a position keyword ("topleft", "bottomright", …) or x/y coordinates, plus the labels and the same col/lty/lwd values as the lines.

Lines with points

type = "b" draws points joined by lines, and type = "o" overplots them:

r · try it yourself
day <- 1:7
steps <- c(6200, 8100, 7400, 10200, 9100, 12000, 4300)
plot(day, steps, type = "o", pch = 16, col = "purple",
     main = "Daily steps", xlab = "Day", ylab = "Steps")
abline(h = mean(steps), col = "grey40", lty = 3)
cat("Average:", round(mean(steps)), "steps\n")
Average: 8186 steps

Time series

R has a time-series class, ts, and plot() knows how to draw it with a proper time axis. The built-in AirPassengers is a monthly series from 1949 to 1960:

r · try it yourself
class(AirPassengers)
start(AirPassengers)
end(AirPassengers)
plot(AirPassengers, col = "navy", main = "Monthly airline passengers (thousands)")
[1] "ts"
[1] 1949    1
[1] 1960   12

Test yourself

How do you turn plot(x, y) into a line graph?

  1. plot(x, y, line = TRUE)
  2. plot(x, y, type = "l")
  3. line(x, y)
  4. plot(x, y, lty = 1)

Which function adds a second line to an existing plot?

  1. plot()
  2. lines()
  3. abline()
  4. add()

What does lty = 2 do?

  1. Doubles the width
  2. Draws a dashed line
  3. Draws two lines
  4. Colours the line red