3

I have two vectors (in a data frame) that I want to plot like this plot(df$timeStamp,df$value), which works nicely by itself. Now the plot is showing the timestamp in a pure numerical way as markers on the x axis.

When I format the vector of timestamps it into a vector of "hh:mm:ss", plot() complains (which makes sense, as the x-axis data is now a vector of strings).

Is there a way to say plot(x-vector, y-vector, label-x-vector) where the label-x-vector contains the elements to display along the x-axis?

2 Answers 2

2

The last part of your general question is done in two commands rather than one. If you look at ?plot.default (linked from ?plot) you'll see an option to leave off the x-axis all together using the xaxt argument (xaxt = 'n'). Do that and then use axis to make the x-axis what you want (check ?axis). I don't know what format your timestamp is currently in so it's hard to help further.

In general it's...

plot(x-vector, y-vector, xaxt = 'n')
axis(1, x-vector, label-x-vector)

(The help for plotting may be just about the messiest part of R-help but once you get used to looking at plot.default, axis, and par you'll start getting a better handle on things)

1
  • Perfect, works like a charm. I guess this "how to browse the help" is still my biggest obstacle at learning R. Thanks!
    – Heiko Rupp
    Dec 28, 2011 at 15:37
2

The standard R plots are pretty good at doing what you want if you give them the correct information. If you can convert your timestamps to actual time objects (Date or POSIXct objects) then plot will tend to do the correct thing. Try the following examples:

tmp <- as.POSIXct( seq(0, length=10, by=60*5), origin='2011-12-28' )
tmp
plot( tmp, runif(10) )
tmp2 <- as.POSIXct( seq(0, length=10, by=60*60*5), origin='2011-12-28' )
tmp2
plot( tmp2, runif(10) )
tmp3 <- as.POSIXct( seq(0, length=10, by=60*60/2), origin='2011-12-28' )
tmp3
plot( tmp3, runif(10) )

In each case the tick labels are pretty meaningful, but if you would like a different format then you can follow @John's example and suppress the default axis, then use axis.POSIXct and specify what format you want.

The examples use equally spaced times (due to my laziness), but will work equally well for unequally spaced times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.