[R] making a Time of Day axis

Alan Jackson Rhelp at ajackson.org
Wed Jun 20 03:37:49 CEST 2007


I am wrestling with time and date data. I came up with a way to plot and
label a histogram with "time of day" on the x-axis, but it seemed like a
lot more work than should be necessary. Is there a better way to do what
I am trying to do?

require(chron)
#	read input data
data = read.table("input.dat", header=T)
#	Create date-time and chron objects
datetime = strptime(paste(data[,3], data[,2]),format="%m/%d/%y %H:%M")
time = times(paste(as.vector(data[,2]), ":00",sep=""))
#	Put it all into a data frame
data = data.frame(time, datetime, data$Trip)
names(data) = c("Time","DateTime","Trip")
attach(data)
#	Create time of day array
times = as.numeric(chron(times = Time))
tod = subset(times, Trip=='m');
#	Plot base histogram
hist(tod, axes=F, main="Morning Bus Arrival Times", xlab="Time", col="blue");
axis(2);
#	where are the tics to be?
tics = seq(min(tod), max(tod), (max(tod)-min(tod))/5);
#	build a labeled x-axis for the plot
axis(1, tics, labels=sub(":00$","",as.character(chron(times=tics, out.format="h:m:s"))));

#	cleanup
detach(data)

--- Data ---
Trip Time Date
a 15:55 05/15/07
m  5:47 05/16/07
a 15:54 05/16/07
m  5:47 05/17/07
a 15:59 05/17/07
m  5:50 05/21/07
m  5:50 05/22/07
a 16:00 05/22/07
m  5:48 05/23/07
m  5:50 05/24/07
a 16:00 05/24/07
m  5:48 05/25/07
m  5:48 05/29/07
a 15:59 05/29/07
m  5:46 05/30/07
m  5:45 05/31/07
a 16:05 05/31/07
m  5:47 06/04/07
a 15:53 06/04/07
m  5:46 06/05/07
m  5:47 06/06/07
a 15:53 06/06/07
m  5:47 06/07/07
a 15:51 06/07/07
m  5:45 06/08/07
f 15:22 06/08/07
m  5:48 06/11/07
m  5:46 06/12/07
m  5:48 06/13/07
m  5:47 06/18/07
a 15:53 06/18/07
m  5:47 06/19/07
a 15:55 06/19/07


-- 
-----------------------------------------------------------------------
| Alan K. Jackson            | To see a World in a Grain of Sand      |
| alan at ajackson.org          | And a Heaven in a Wild Flower,         |
| www.ajackson.org           | Hold Infinity in the palm of your hand |
| Houston, Texas             | And Eternity in an hour. - Blake       |



More information about the R-help mailing list