Reputation: 6488
I have three data frames df1
, df2
, df3
in the following format
datetime value
2012-01-02 00:00:00 1.2
2012-01-02 00:15:00 1.7
2012-01-02 00:30:00 0.5
2012-01-02 00:45:00 0.8
datetime value
2012-01-03 00:00:00 0.4
2012-01-03 00:15:00 1.1
2012-01-03 00:30:00 1.8
2012-01-03 00:45:00 0.7
datetime value
2012-01-04 00:00:00 2.9
2012-01-04 00:15:00 0.7
2012-01-04 00:30:00 1.3
2012-01-04 00:45:00 0.3
All three data frames have different dates, the datetime
is in POSIXlt
format.
Since, time index are same, I want to plot all the lines on the same plot. But I am not sure how to extract time only. I have done following so far:
library(chron)
timeOnly = times(format(df1$datetime, "%H:%M:%S"))
plot(timeOnly, df1$value)
But the x-axis tick labels go from 0 to 1
, instead of 00:00:00 to 23:45:00
Upvotes: 1
Views: 1428
Reputation: 4092
Edited to have different dates, This is how I would solve it, add a class, and then rbind the dataframes and plot it:
library(lubridate)
set.seed(1)
df1 <- data.frame(date_time = seq(ymd_hm('2012-01-02 00:00'),ymd_hm('2012-01-02 23:45'), by = '15 min')
, value = rnorm(4, mean = 1, sd =0.2), class = "a")
set.seed(2)
df2 <- data.frame(date_time = seq(ymd_hm('2012-01-03 00:00'),ymd_hm('2012-01-03 23:45'), by = '15 min')
, value = rnorm(4, mean = 1, sd =0.2), class = "b")
set.seed(3)
df3 <- data.frame(date_time = seq(ymd_hm('2012-01-04 00:00'),ymd_hm('2012-01-04 23:45'), by = '15 min')
, value = rnorm(4, mean = 1, sd =0.2), class = "c")
df <- rbind(df1,df2, df3)
df$time <- as_date(hm(paste(hour(df$date_time),minute(df$date_time), sep=":")))
library(ggplot2)
ggplot(df, aes(x = time, y = value)) + geom_line(aes(color = class))+ scale_x_datetime(date_labels = "%H %M")
Upvotes: 2