GGPLOT2 - 在同一个情节情节多个模型(ggplot2 - plot multiple mo

2019-07-03 15:58发布

我从不同的数据集测量相同的两个变量衍生的线性和非线性模型的列表xy ,我想使用相同的情节绘制stat_smooth 。 这是为了能够容易地比较之间的关系的形状xy跨数据集。

我试图找出做到这一点的最有效途径。 现在我正在考虑创建一个空ggplot对象,然后使用某种类型的循环或lapply依次添加到该对象,但这被证明是比我想象的更困难。 当然,这将是最容易简单地提供模型ggplot但据我所知,这是不可能的。 有什么想法吗?

下面是一个简单的示例数据集中,只要使用两种型号,一种线性和一个指数发挥:

df1=data.frame(x=rnorm(10),y=rnorm(10))
df2=data.frame(x=rnorm(15),y=rnorm(15))

df.list=list(lm(y~x,df1),nls(y~exp(a+b*x),start=list(a=1,b=1),df2))

和两个独立的例子图:

ggplot(df1,aes(x,y))+stat_smooth(method=lm,se=F)
ggplot(df2,aes(x,y))+stat_smooth(method=nls,formula=y~exp(a+b*x),start=list(a=1,b=1),se=F)

Answer 1:

我觉得这里的答案是让你想运行此在X和Y的公共范围,并从那里走。 您可以使用预测模型各拉出一条曲线,使用l_ply上的层添加到ggplot。

d

f1=data.frame(x=rnorm(10),y=rnorm(10))
df2=data.frame(x=rnorm(15),y=rnorm(15))

df.list=list(lm(y~x,df1),nls(y~exp(a+b*x),start=list(a=1,b=1),df2))


a<-ggplot()


#get the range of x you want to look at
x<-seq(min(c(df1$x, df2$x)), max(c(df1$x, df2$x)), .01)

#use l_ply to keep adding layers
l_ply(df.list, function(amod){

  #a data frame for predictors and response
  ndf <- data.frame(x=x)

  #get the response using predict - you can even get a CI here
  ndf$y <- predict(amod, ndf)

  #now add this new layer to the plot
  a<<- a+geom_line(ndf, mapping=(aes(x=x, y=y)))

} )

a

或者,如果你想与型号或某事一个很好的色键:

names(df.list) <- 1:length(df.list)
modFits <- ldply(df.list, function(amod){
  ndf <- data.frame(x=x)

  #get the response using predict - you can even get a CI here
  ndf$y <- predict(amod, ndf)

  ndf

  })


qplot(x, y, geom="line", colour=.id, data=modFits)


Answer 2:

编辑:请注意,OP改变的问题这个答案被张贴后,

合并数据成单个数据帧,与一个新的列表示示范,然后使用ggplot模型之间进行区分:

df1=data.frame(x=rnorm(10),y=rnorm(10))
df2=data.frame(x=rnorm(10),y=rnorm(10))

df1$model <- "A"
df2$model <- "B"

dfc <- rbind(df1, df2)

library(ggplot2)
ggplot(dfc, aes(x, y, group=model)) + geom_point() + stat_smooth(aes(col=model))

这将产生:



文章来源: ggplot2 - plot multiple models on the same plot
标签: r ggplot2