如何使用自动方程在单个散点图中绘制三个或更多变量?

How to plot three or more variables in a single scatterplot with automated equations?

我想在一个散点图中绘制来自 3 个不同数据帧的 2 个变量,并自动绘制每个线性关系的方程。我正在使用以下代码。但是我有两个问题:

  1. 我得到相同值的图,而不是整个范围的图(例如 df1 =700 值、df2= 350 值、df3=450 值)。省略 NA 的作用是什么?因为我两种方法都试过了,我仍然得到相同的情节

  2. 我只能将方程添加为文本,这意味着 运行 lm 函数,然后在图中手动添加关系。我需要自动执行此操作。

我使用的代码是:

ggplot(df1, aes(x=noxppb, y=OX, colour = "red")) +
  geom_point(colour = "red", shape=2) +    # Use hollow circles
  geom_smooth(method=lm, se = FALSE) + 
  geom_point(data = df1, aes(x=noxppb, y=OX)) +
  geom_point(colour = "blue", shape=3) +
  geom_smooth(method = lm, se = F, colour = "blue", data = df2, aes(x=noxppb, y=OX)) +
  geom_point(colour = "green", shape=4) +
  geom_smooth(method = lm, se = F, colour = "green", data = df3, aes(x=noxppb, y=OX))

我得到以下图像:

不过我需要类似这样的东西:

试试这个,

d <- plyr::mdply(data.frame(a=c(1,2,3), b=c(-1,0,1)), 
                 function(a,b) data.frame(x=seq(0,10), y=jitter(a*seq(0,10)+b)))


equationise = function(d, ...){
  m = lm(y ~ x, d)
  eq <- substitute(italic(y) == a + b %.% italic(x), 
                                        list(a = format(coef(m)[1], ...), 
                                             b = format(coef(m)[2], ...)))
  data.frame(x = Inf, y = d$y[nrow(d)], 
             label = as.character(as.expression(eq)),  
             stringsAsFactors = FALSE)
}


eqs <- plyr::ddply(d, "a", equationise, digits = 2)


ggplot(d, aes(x=x, y=y, colour = factor(a))) + 
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_label(data=eqs, aes(label = label), parse=TRUE, hjust=1)