Home » How to Plot the Rows of a Matrix in R (With Examples)

How to Plot the Rows of a Matrix in R (With Examples)

by Tutor Aspire

Occasionally you may want to plot the rows of a matrix in R as individual lines. Fortunately this is easy to do using the following syntax:

matplot(t(matrix_name), type = "l")

This tutorial provides an example of how to use this syntax in practice.

Example: Plot the Rows of a Matrix in R

First, let’s create a fake matrix to work with that contains three rows:

#make this example reproducible
set.seed(1)

#create matrix
data int(50, 21), nrow=3)

#view matrix
data

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    4   34   14   21    7   40   12
[2,]   39   23   18   41    9   25   36
[3,]    1   43   33   10   15   47   48

Next, let’s use matplot to plot the three rows of the matrix as individual lines on a plot:

matplot(t(data), type = "l")

Plot rows of matrix in R

Each line in the plot represents one of the three rows of data in the matrix.

Note: The matplot function is used to plot the columns of a matrix. Thus, we use t() to transpose the matrix so that we instead plot the rows.

We can also modify the width of the lines and add some labels to the plot:

matplot(t(data),
        type = "l",
        lwd = 2,
        main="Plotting the Rows of a Matrix",
        ylab="Value")

Example of plotting a matrix in R


You can find more R tutorials on this page.

You may also like