在R中绘制两个不同日期的时间序列

时间:2016-06-16 05:05:59

标签: r plot ggplot2

我有两个数据集,如下所示,我试图使用ggplot2或常规绘图在一个图中绘制它们:

df1
date                count
2014-09-10 07:14:00 0.07253886
2014-09-10 07:19:00 0.03626943
2014-09-10 07:24:00  0.07253886
2014-09-10 07:29:00  0.19689119
2014-09-10 07:34:00  0.13989637
2014-09-10 07:39:00  0.88601036

df2
date                count
2014-09-10 11:25:00  1.00000000
2014-09-10 11:30:00  0.47058824
2014-09-10 11:35:00  0.00000000
2014-09-10 11:40:00  0.11764706
2014-09-10 11:45:00  0.00000000
2014-09-10 11:50:00  0.05882353

正如您所看到的,数据框具有不同的日期值(因此您不能简单地按日期列合并两个数据框),尽管它们以5分钟的间隔分隔。我所要做的就是让一个图从最小日期和范围开始到这两个数据框的最大日期,同时在每个时间间隔内正确绘制点击次数。

1 个答案:

答案 0 :(得分:2)

您可以为df1和&创建新的“类型”列。然后df2将它们绑定在一起,如@thelatemail的评论

> df <- rbind(df1, df2)
> dput(df)
    structure(list(Date = structure(c(1410358440, 1410358740, 1410359040, 
    1410359340, 1410359640, 1410359940, 1410373500, 1410373800, 1410374100, 
    1410374400, 1410374700, 1410375000), tzone = "", class = c("POSIXct", 
    "POSIXt")), count = c(0.07253886, 0.03626943, 0.07253886, 0.19689119, 
    0.13989637, 0.88601036, 1, 0.47058824, 0, 0.11764706, 0, 0.05882353
    ), type = c("df1", "df1", "df1", "df1", "df1", "df1", "df2", 
    "df2", "df2", "df2", "df2", "df2")), .Names = c("Date", "count", 
    "type"), row.names = c(NA, 12L), class = "data.frame")

现在使用ggplot

进行绘图相对容易
library(ggplot2)
ggplot(df, aes(x = Date, y = count, color = type)) + geom_line() + theme_bw()

enter image description here