[R] Graphing lines of different lengths

Jim Lemon jim at bitwrit.com.au
Fri Feb 17 08:32:49 CET 2012


On 02/17/2012 06:42 AM, Jordan Patricia Sinclair wrote:
> Hello all.
> I need to graph multiple lines of different lengths on the same graph.  When I try to add lines I get an error due to different lengths.  The only thing I could find when reading up on it was that 'if the data are inputted separately they must be of the same length'.
> Could someone please let me know how to input the data together?
> Thanks for any help,
> Jordan
>
Hi Jordan,
If you want to plot all your lines at once, you will have to pad the 
shorter one with NAs. I'm assuming that your missing points are on the 
ends of the lines.

line1<-1:10
line2<-c(2,3,4,2,3,4,rep(NA,4))
line3<-c(NA,4,5,6,7,2,3,4,5,NA)

matplot(cbind(line1,line2,line3),type="b")

However, if you want to plot your original vectors of values without 
padding, you can do it like this, by specifying the x values as well:

plot(line1)
line2<-c(2,3,4,2,3,4)
lines(1:6,line2)
line3<-c(4,5,6,7,2,3,4,5)
lines(2:9,line3)

Jim



More information about the R-help mailing list