user3275911
user3275911

Reputation: 51

plotting each column of a matrix individually in a single graph in R

enter image description hereI have a 10x10 matrix and I want to plot each column(in the form of lines) in the following way
1. There should be one y-axis which will cover the scale of all columns of matrix.
2. There should be single x-axis with 10 points(= the number of columns).
3. the first column of matrix should be plotted within the point-1 and point-2 of x-axis, the second column of matrix within the point 2 and point-3, third column within the point-3 and point-4 and so on....
I have seen already posts, but all are multiple plots which are not according to my requirements. Could you please help me that how this can be done in R

Upvotes: 1

Views: 1790

Answers (2)

Jthorpe
Jthorpe

Reputation: 10204

Here's how you do it with matplot.

matplot(y = myData,
       ,x = matrix(seq(prod(dim(myData)))/nrow(myData),
                   nrow=nrow(myData),byrow=F)
             - 1/nrow(myData) + 1)

The trick is constructing the right matrix for the x values.

Upvotes: 3

josliber
josliber

Reputation: 44340

You could convert your data from wide to long format and then use a standard plotting utility like ggplot to appropriately group your data and position it:

# Build a sample matrix, dat
set.seed(144)
dat <- matrix(rnorm(100), nrow=10)

# Build a data frame, to.plot, where each element represents one value in the matrix
to.plot <- expand.grid(row=factor(seq(nrow(dat))), col=factor(seq(ncol(dat))))
to.plot$dat <- dat[cbind(to.plot$row, to.plot$col)]
to.plot$col <- as.factor(to.plot$col)

# Plot
library(ggplot2)
ggplot(to.plot, aes(x=as.numeric(col)+(row-1)/max(row), y=dat, group=col, col=col))
 + geom_line() + scale_x_continuous(breaks=1:10) + xlab("Column")

enter image description here

Upvotes: 3

Related Questions