Frédéric Santos' notebook
Emacs and R tricks for anthropologists and archaeologists.
02 déc. 2020

# How to define custom line types with R?

There are already six default line types defined in R; but how can one create a new, custom line type? It’s quite easy to do this in Python… and just as easy to do in R!

## 1 Default line types in R

The six default line types available in R can be viewed in Figure 1.

library(poliscidata)
lineType() Figure 1: The six default line types with R.

They can be used either by their index (0 to 6) or their name ("blank", "solid", …), as illustrated on Figure 2. Note how the argument lty is specified in the functions plot() and lines().

x <- seq(from = 0, to = 4, by = 0.1)
## Plot two curves:
plot(x = x, y = I(x^2), type = "l",
lty = 3, lwd = 2, col = "red",
xlab = NA, ylab = NA)
lines(x, exp(x), type = "l", lwd = 2,
lty = "dotdash", col = "blue")
## Add legend:
legend("topleft", lty = c(3, 4), col = c("red", "blue"),
lwd = 2, legend = c("x^2", "exp(x)")) Figure 2: Using different line types for a simple plot in R.

## 2 Defining custom line types

Directly from the help page of the function par():

     ‘lty’ The line type.  Line types can either be specified as an
integer (0=blank, 1=solid (default), 2=dashed, 3=dotted,
4=dotdash, 5=longdash, 6=twodash) or as one of the character
strings ‘"blank"’, ‘"solid"’, ‘"dashed"’, ‘"dotted"’,
‘"dotdash"’, ‘"longdash"’, or ‘"twodash"’, where ‘"blank"’
uses ‘invisible lines’ (i.e., does not draw them).

Alternatively, a string of up to 8 characters (from ‘c(1:9,
"A":"F")’) may be given, giving the length of line segments
which are alternatively drawn and skipped.


Here, the last paragraph is precisely what we need to define more line types: we just need to indicate a sequence of hexadecimal characters giving (alternatively) the length of the segments and the blanks separating them. Figure 3: Some examples of line types defined with two, four or six hexadecimal characters.

We use those new examples to update Figure 2:

x <- seq(from = 0, to = 4, by = 0.1)
## Plot two curves:
plot(x = x, y = I(x^2), type = "l",
lty = "3D", lwd = 2, col = "red",
xlab = NA, ylab = NA)
lines(x, exp(x), type = "l", lwd = 2,
lty = "159D", col = "blue")
## Add legend:
legend("topleft", lty = c("3D", "159D"), col = c("red", "blue"),
lwd = 2, legend = c("x^2", "exp(x)")) Figure 4: Using new line types in simple plots.