1

I'm trying to plot a dataset consisting of numbers and some NA entries in R.

V1,V2,V3
 2, 4, 3
NA, 5, 4
NA,NA,NA
NA, 7, 3
 6, 6, 9

Should return the same lines in the plot, as if I had entered:

V1,V2,V3
 2, 4, 3
 3, 5, 4
 4, 6, 3.5
 5, 7, 3
 6, 6, 9

What I need R to do is basically plotting the dataset as points, an then connect these points by straight lines, which - due to the size of the dataset - would be much more efficient then the actual calculation of each interpolated value within the dataset. So it should not happen by computing interpolations (via loop or something like that), but instead just on the graph.

Since the dataset has multiple columns and I am currently using Rs matplot function to visualize it, there should be a way to add multiple NA-adjusted lines (as in matpot() or lines() for example). Hence plot(...) would be problematic because it overwrites the current graphics device.

Stephen Rewitz
  • 43
  • 1
  • 2
  • 5

1 Answers1

0
mydf <- data.frame(V1=c(2,NA,NA,NA,6),V2=c(4,5,NA,7,6),V3=c(3,4,NA,3,9))

plot(NA,xlim=c(0,nrow(mydf)+1),ylim=c(min(mydf,na.rm=TRUE)-1,max(mydf,na.rm=TRUE)+1))
mapply(function(x,color){
    dat <- na.omit(cbind(1:length(x),x))
    lines(dat[,1],dat[,2],col=color)
},mydf,c("red","blue","green"))

enter image description here

Thomas
  • 43,637
  • 12
  • 109
  • 140
  • Thanks a lot! Right what I was looking for! Is there a way to rainbow() color the lines differently to avoid confusion when viewing? Adding behind lines(dat[,1],dat[,2],col = x) outputs repetitive colors (in this case two times blue). col = rainbow(length(..)) did not work either.. – Stephen Rewitz Aug 01 '13 at 01:26
  • @StephenRewitz See my edit, which uses `mapply` and a vector of colors. – Thomas Aug 01 '13 at 06:16
  • Which part of the answer is responsible? The ylim parms? – Phil Goetz Nov 30 '16 at 06:59