0

Let say i have a data like this

M<- matrix(rnorm(20),20,5)
x <- as.matrix(sort(runif(20, 5.0, 7.5)))

The M has 5 columns with the same values which I want to plot it but I don't want to plot them on each other. I want to show them with a space. What I do is like below

plot(x, M[,1], ylim=range(M), ann=FALSE, axes=T,type="l")
Colm <- 2:ncol(M)
lapply(seq_along(Colm),function(i){
  lines(x, M[,i], col=Colm[i])
})

Is there any way to make a distance between each line in plot ?

eipi10
  • 91,525
  • 24
  • 209
  • 285
nik
  • 2,500
  • 5
  • 21
  • 48

2 Answers2

0

You can add a small change to each y value to shift each line slightly.

set.seed(595)
M <- matrix(rnorm(20),20,5)
x <- as.matrix(sort(runif(20, 5.0, 7.5)))

plot(NA, ylim=range(M), xlim=range(x), ann=FALSE, axes=T, type="l")

# Amount by which to shift each y value
eps = seq(-0.1, 0.1, length.out=ncol(M))

lapply(1:ncol(M), function(i){
   lines(x, M[,i] + eps[i], col=i)
})

enter image description here

UPDATE: In answer to your comment, I think the following is probably what's happening: In your sample code, x is a matrix, which behaves essentially the same as a vector when the matrix has only one column. Thus, x will return a data vector, so you can just use the object x directly in the lines function. However, if you're importing x as a data frame (for example, using x=read.table("x.txt", header=TRUE), then you need to use lines(x[,1], M[,i] + eps[i], col=i) in your code in order to get the vector of data in the first column of the data frame x.

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • I tried your function on my real data but I got error that x and y are not with the same length , the M ca be find here https://gist.github.com/anonymous/1f401d5c3b88fda66c01d7eabb3c6514 and the x can be find here https://gist.github.com/anonymous/95fff534dbcf2d15d2b7a51fb78b87dd – nik Apr 07 '16 at 17:50
  • Those two data sources have the same number of rows, but check the actual data objects in R to make sure `x` and `M` in your `lines` function really do have the same number of values. – eipi10 Apr 07 '16 at 20:55
  • is there any other way to plot it which I can use for my real data? – nik Apr 08 '16 at 09:21
  • See update to my answer for the likely reason for the error you're getting and what to do about it. – eipi10 Apr 08 '16 at 15:43
0

If you use ggplot you can do this easily using the alpha command as indicated in this post:

Overlapping Lines in ggplot2

and you could also jitter the lines using code from this post..

How to jitter lines in ggplot2

Community
  • 1
  • 1
Bill Perry
  • 463
  • 1
  • 5
  • 13