R ts.plot(): order of series

10,184
ts.plot(df,col=c(rep("blue",3),rep("black",3)))

I think it is plotting absolutely as specified in the order A-B-C-D-E-F. So...

A     B     C     D     E     F
Blue  Blue  Blue  Black Black Black 

enter image description here

If you match up your values for A/B/C...

          A  B    C
2003-07 445 48 1126
2003-08 429 77 1179
2003-09 421 80 1077

...you will see the three blue lines are those going from 445->429->421 & 48->77->80 & 1126->1179->1077, which actually matches what you specified you want.

As an aside, you could simplify your plot call to be:

ts.plot(df,col=rep(c("black","blue"),each=3))

...by using the each= part of the function call.

EDIT::

Looking at your dput, it looks like your graph is also plotting your labels df$X as the values 1,2,3 since it is a factor and gets interpreted as such when plotting.

Try this bit of code to remove the labels from your original plot and add them back in again:

ts.plot(df[-1],col=c(rep("blue",3),rep("black",3)),gpars=list(xaxt="n"))
axis(1,labels=as.character(df$X),at=1:3)
Share:
10,184
Hugh
Author by

Hugh

Updated on June 04, 2022

Comments

  • Hugh
    Hugh almost 2 years

    I have a data frame like

        A   B   C   D   E   F
    2003-07 445 48  1126    512 277 677
    2003-08 429 77  1179    583 320 675
    2003-09 421 80  1077    488 288 627
    

    I want to plot these time series on the same graph. I also want A B C to have the same colour (blue) and the others to be black. So I use

    ts.plot(df,col=c(rep("blue",3),rep("black",3)))
    

    This creates the correct time series plot, except the colours are applied to the wrong series: A B C are a mix of blue and black and so are D E F. (Note that the real data frame has a lot more columns if that is the source of the problem.)

    What order does ts.plot() use?

    EDIT

    df <- structure(list(X = structure(1:3, 
    .Label = c("2003-07", "2003-08", "2003-09"), class = "factor"), 
     A = c(445L, 429L, 421L), B = c(48L, 77L, 80L),
     C = c(1126L, 1179L, 1077L), D = c(512L, 583L, 488L ), 
     E = c(277L, 320L, 288L), FF = c(677L, 675L, 627L)), 
    .Names = c("X", "A", "B", "C", "D", "E", "FF"), 
    class = "data.frame", row.names = c(NA, -3L))
    
  • Hugh
    Hugh over 11 years
    OK, that's very strange. My output is different. (The third series from the top is blue for instance.) I'm using the most recent version of R 64-bit. Anything I can do to troubleshoot?
  • thelatemail
    thelatemail over 11 years
    If you type dput(df) and paste the output here as @mnel suggested we might be able to see if there is something strange going on that might not be immediately obvious.
  • Hugh
    Hugh over 11 years
    OK, after using different colours for each series, it seems to be going 2, 3, 4, 5, 6, 1.