我有以下格式的三个数据框df1
,df2
,df3
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
所有三个数据框都有不同的日期,datetime
格式为POSIXlt
。
由于时间索引相同,我想在同一个图上绘制所有线条。但我不知道如何只提取时间。到目前为止,我已经完成了以下任务:
library(chron)
timeOnly = times(format(df1$datetime, "%H:%M:%S"))
plot(timeOnly, df1$value)
但x轴刻度标签来自0 to 1
,而不是00:00:00 to 23:45:00
答案 0 :(得分:2)
编辑有不同的日期,这是我如何解决它,添加一个类,然后rbind数据帧并绘制它:
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")