-2

使用 ggplot2 包,我想获得一个包含两个时间序列的图,这些时间序列在不同日期有数据点。

例如,一个数据框如下所示:

date1, value1  
2010-01-05, 2921.74  
2010-01-08, 2703.89  
2010-01-14, 3594.21  
2010-01-20, 3659.22  

另一个数据框看起来像

date2, value2  
2010-01-01, 285.85  
2010-01-02, 229.20  
2010-01-05, 333.91  
2010-01-06, 338.27  
2010-01-07, 272.85  
2010-01-08, 249.04  
2010-01-09, 240.07  
2010-01-10, 255.06  
2010-01-11, 275.42  
2010-01-12, 252.39  

我想将这两个时间序列绘制在同一个图中,日期在 X 轴上,值在 Y 轴上。{base} 情节相当容易,但我想用 ggplot 来做。

4

1 回答 1

2

您可以简单地使用带有不同参数的两个geom_point's :data

ggplot(aes(x = date, y = value)) + geom_point(data = df1) + geom_point(data = df2)

这假设您的数据集被称为df1and df2,并且它们具有相同的列名。

更简单的方法是将两个数据集组合起来,并添加一个标识列:

df1$id = "one"
df2$id = "two"
df = rbind(df1, df2)
ggplot(df, aes(x = date, y = value, color = id)) + geom_point()

最后一个解决方案更符合ggplot2. 请注意,这种方法对geom_line.

一个例子:

ggplot(diamonds, aes(x = carat, y = depth, color = cut)) + geom_point()

在此处输入图像描述

于 2013-03-07T08:35:27.323 回答