Plotting POSIXct timestamp series with ggplot2
Asked Answered
T

1

12

I would like to plot the results of a load test. Each row contains a timestamp in seconds and the response time for the request. For example:

timestamp <- c(1441229131, 1441229132, 1441229133, 1441229134, 1441229135)
response.time <- c(22, 48, 48, 59, 52)
lt1 <- data.frame(timestamp, response.time)
lt1$datetime <- as.POSIXct(lt1$timestamp, origin="1970-01-01", tz="GMT")

However, when I try to plot this, the x axis shows wierd numbers instead od a properly formatted date.

g1 <- ggplot(lt1, aes(datetime, response.time))
g1 <- g1 + geom_point()
g1 <- g1 + theme(axis.text.x=element_text(angle=90, hjust=1))
g1

enter image description here

Threephase answered 2/9, 2015 at 22:13 Comment(0)
F
20

You need to specify what you want on the x-axis using the library scales and the function scale_x_datetime:

library(scales)
ggplot(lt1, aes(datetime, response.time)) +
       geom_point() +
       theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
       scale_x_datetime(labels = date_format("%H:%M:%S"))

enter image description here

for more info, see ?scale_x_datetime, ?date_format and ?strptime

Fredra answered 2/9, 2015 at 22:28 Comment(1)
in dplyr 1.0.0, date_format() is deprecated, and should be replaced by label_date(). If you don't want to load the scales library as in this example, just use the long form scales::label_date()Davedaveda

© 2022 - 2024 — McMap. All rights reserved.