[R] Help with matplot

Marc Schwartz marc_schwartz at comcast.net
Thu Nov 13 17:36:10 CET 2008


on 11/13/2008 09:39 AM mentor_ wrote:
> Hi,
> 
> two days ago I have asked the list if there is a better way to plot a matrix
> using
> the following plot command:
> 
> plot(matrix[1,], type="l")
> for (i in 2:dim(matrix)[1]) {
>        lines(matrix[i,], type="l")
> }
> 
> I have been told to use the matplot function, but unfortunately I matplot
> does not plot my matrix
> as I would like the matrix to be plotted...
> Each row in the matrix should be plotted as a time series plot. The columns
> should reflect the "time"
> The matrix looks like this:
> 
>           [,1]      [,2]      [,3]      [,4]      [,5]       [,6]
> [1,] 10.795525 17.742121 -1.668664  7.410594 10.229107 -0.7402613
> [2,]  9.335885 10.472469  9.503561  9.815167 16.073518 21.1387238
> [3,] 16.818605  5.354479 10.921837  5.202947  4.730314  2.3975041
> [4,]  9.773960 10.081033  3.538419 16.913288 10.623028  7.8052165
> [5,]  8.473132 13.775806  3.739209 15.224250  6.339220  7.3409747
> 
> I tried this with matplot:
> m <- matrix(rnorm(30, 10, 5), ncol=6)
> time <- matrix(rep(1:6,5), nrow=5, byrow=TRUE)
> matplot(time, m, type="l", col="black")
> 
> Any help would be appreciate!
> Thanks!

What you really want is simply:

  matplot(m, type = "l", col = "black")

Note from ?matplot:

x,y 	vectors or matrices of data for plotting. The number of rows
        should match. _If one of them are missing, the other is taken as
        y and an x vector of 1:n is used_

Thus, if you simply pass the matrix 'm', an x vector of 1:5 is used by
default and each column of 'm' is plotted against 1:5.

If you, for some reason, wanted to create the 'time' matrix, it should be:

> matrix(1:5, nrow = 5, ncol = 6)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    1    1    1
[2,]    2    2    2    2    2    2
[3,]    3    3    3    3    3    3
[4,]    4    4    4    4    4    4
[5,]    5    5    5    5    5    5

so that the 'x' values are ordered within each column, rather than by
row. However, note that based upon the above, you do not need a matrix.
A vector of 1:5 would suffice, as in:

  matplot(1:5, m, type = "l", col = "black")

HTH,

Marc Schwartz



More information about the R-help mailing list