[R] Show time in x-axis

Jim Lemon jim at bitwrit.com.au
Mon Nov 11 12:44:58 CET 2013


On 11/11/2013 09:07 PM, mohan.radhakrishnan at polarisft.com wrote:
> Hi,
>              I am trying to show time( HH:MM:SS) in my x-axis. I have these
> two questions.
>
> 1. The error in the code is
>
> Error in axis(1, at = data$Time, labels = data$Time, las = 2, cex.axis =
> 1.2) :
>    (list) object cannot be coerced to type 'double'
>
> Should I use 'POSIXCt' or 'strptime' ?
>
> 2. I have times that are repeated because it is the next or previous day.
> But I want to show the times and data points in sequence - as they are in
> the data frame - along the axis.
>
> Thanks,
> Mohan
>
>          X1       X2             X3                      X4
> OldGenAfterFullGC      X6               X7      PermGenAfterFullGC  Time
> 1        0              3285    873856          3456              3285
> 1256128         12862              12862                19:36:16
> 2     3285      30437   873856          31324             30437 1256128
> 39212              39212                19:36:26
> 3   312755      313565   873856         313843            313565  1214080
> 182327             182327               20:36:27
> 4   313565      281379  873856          313789            281379 1213248
> 182338             147729               21:36:29
> 5        0              3285    873856          3456              3285
> 1256128         12862              12862                19:36:16
>
> plot(data$Time,levels(data$PermGenAfterFullGC)[data$PermGenAfterFullGC],col="darkblue",pch=2,type="b",
> ylab="Megabytes", xlab="Time",las=2,lwd=2, cex.lab=1,cex.axis=1,xaxt="n")
>
> axis(1, at = data$Time, labels = data$Time, las = 2,cex.axis=1.2)
> text(data$Time,data$Time, data$Time, 2, cex=1.45)
>
>
Hi Mohan,
Yes, you probably want to convert the "Time" variable. However, to 
answer both questions in one, you also probably want to stick a starting 
date on your times, incrementing this whenever a time is less than the 
previous one:

# this will produce times for the current date
data$Time1<-strptime(data$Time,"%H:%M:%S")
offset<-0
lasttime<-0
for(timedate in 1:length(data$Time1)) {
  if(as.numeric(data$Time1[timedate]) < lasttime) offset<-offset + 86400
  data$Time1[timedate]<-data$Time1[timedate]+offset
  lasttime<-data$Time1[timedate]
}

Then you can use "Time1" as the "at" argument, and "Time" as the 
"labels" argument to axis.

Jim



More information about the R-help mailing list