R Language Base Plotting Matplot


matplot is useful for quickly plotting multiple sets of observations from the same object, particularly from a matrix, on the same graph.

Here is an example of a matrix containing four sets of random draws, each with a different mean.

xmat <- cbind(rnorm(100, -3), rnorm(100, -1), rnorm(100, 1), rnorm(100, 3))
#          [,1]        [,2]       [,3]     [,4]
# [1,] -3.072793 -2.53111494  0.6168063 3.780465
# [2,] -3.702545 -1.42789347 -0.2197196 2.478416
# [3,] -2.890698 -1.88476126  1.9586467 5.268474
# [4,] -3.431133 -2.02626870  1.1153643 3.170689
# [5,] -4.532925  0.02164187  0.9783948 3.162121
# [6,] -2.169391 -1.42699116  0.3214854 4.480305

One way to plot all of these observations on the same graph is to do one plot call followed by three more points or lines calls.

plot(xmat[,1], type = 'l')
lines(xmat[,2], col = 'red')
lines(xmat[,3], col = 'green')
lines(xmat[,4], col = 'blue')

Figure using plot and lines

However, this is both tedious, and causes problems because, among other things, by default the axis limits are fixed by plot to fit only the first column.

Much more convenient in this situation is to use the matplot function, which only requires one call and automatically takes care of axis limits and changing the aesthetics for each column to make them distinguishable.

matplot(xmat, type = 'l')

Figure using matplot

Note that, by default, matplot varies both color (col) and linetype (lty) because this increases the number of possible combinations before they get repeated. However, any (or both) of these aesthetics can be fixed to a single value...

matplot(xmat, type = 'l', col = 'black')

Figure using matplot with all black lines

...or a custom vector (which will recycle to the number of columns, following standard R vector recycling rules).

matplot(xmat, type = 'l', col = c('red', 'green', 'blue', 'orange'))

Figure using matplot with custom-colored lines

Standard graphical parameters, including main, xlab, xmin, work exactly the same way as for plot. For more on those, see ?par.

Like plot, if given only one object, matplot assumes it's the y variable and uses the indices for x. However, x and y can be specified explicitly.

matplot(x = seq(0, 10, length.out = 100), y = xmat, type='l')

Setting a value for the x axis

In fact, both x and y can be matrices.

xes <- cbind(seq(0, 10, length.out = 100),
             seq(2.5, 12.5, length.out = 100),
             seq(5, 15, length.out = 100),
             seq(7.5, 17.5, length.out = 100))
matplot(x = xes, y = xmat, type = 'l')

Matrix input for x and y