I have data with one column of being timestamp in format dd.mm.yyyy HH:MM:SS
.
This is how the data looks like:
> data$TimeStamp
[1] "14.3.2017 10:00:00" "14.3.2017 10:00:01" "14.3.2017 10:00:02" "14.3.2017 10:00:03" "14.3.2017 10:00:04" "14.3.2017 10:00:05"
My goal is to produce plots with timestamps on x-axis
with only time HH:MM:SS
as labels but the time span may be longer than one day.
So for example my x-axis
labels could look like this at each tick with one hour intervals:
22:00:00 23:00:00 00:00:00 01:00:00 02:00:00
I have thought about splitting the character string into date and time and convert time into seconds before plotting but I am willing to hear any alternative paths to do this since I probably will have issues with automatically assigning axis labels properly.
Given
df <- data.frame(
x=Sys.time()+runif(100, 1, 60*60*24*2),
y=runif(100))
df$x <- as.character(df$x)
str(df)
# 'data.frame': 100 obs. of 2 variables:
# $ x: chr "2017-06-13 18:33:35" "2017-06-14 11:51:49" "2017-06-12 21:51:10" ...
# $ y: num 0.634 0.738 0.334 0.885 0.461 ...
you could define a sort of labeling function
f <- function(x) as.POSIXct(levels(cut(x, breaks = "2 hours")))
and then do
df$x <- as.POSIXct(df$x)
plot(y~x, df, xaxt="n")
with(df, axis(1, at=f(x), labels=format(f(x), "%H:%M:%S")))