R语言:如何使用ggplot2在回归线的一个图上绘制多个向量?

时间:2015-06-08 02:42:29

标签: r ggplot2

例如,如果我有以下数据框(DF),如何使用ggplot2在一个图表中将VAR1与年份和VAR2与年份进行对比?并添加回归线?

year  VAR1  VAR2
2001    10    12
2002    30    12
2003    20    15

我可以使用qplot(year, VAR, data=DF, geom=c("point", "smooth"), method="lm", se=FALSE)获取一个图表,但不知道如何添加另一个图表。我是否需要以某种方式重新排列数据以使用因子,然后使用facets属性?

1 个答案:

答案 0 :(得分:3)

您希望首先将VAR1VAR2收集到同一列中,这可以使用tidyr包中的gather函数完成:

library(tidyr)
DF2 <- gather(DF, type, value, VAR1, VAR2)

这将使DF2变得整洁,在绘图上为每个点添加一行(有关整洁数据和采集操作的更多信息,请参阅this paper):

  year type value
1 2001 VAR1    10
2 2002 VAR1    30
3 2003 VAR1    20
4 2001 VAR2    12
5 2002 VAR2    12
6 2003 VAR2    15

完成此操作后,您可以使用以下方法创建包含两个变量的图:

ggplot(DF2, aes(year, value, color = type)) +
    geom_point() +
    geom_smooth(method = "lm")

如果您希望将VAR分成两个子图(facet),则可以改为:

ggplot(DF2, aes(year, value)) +
    geom_point() +
    geom_smooth(method = "lm") +
    facet_wrap(~ type)