r - ggplot2 - 在同一张图上绘制多个模型

标签 r ggplot2

我有一个来自不同数据集的线性和非线性模型列表,这些模型测量相同的两个变量 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)

最佳答案

我认为这里的答案是获得一个共同的 X 和 Y 范围,你想运行它,然后从那里开始。您可以使用 predict 从每个模型中拉出一条曲线,然后使用 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)

关于r - ggplot2 - 在同一张图上绘制多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294445/

相关文章:

r - r 中的手动 PIL 逊相关

R Shiny : How to have sequential Modals in for loop

r - 在ggplot2中调整图例标题的位置和字体大小

r - ggplot 函数内 aes(...) 中变量的范围

r - 在 R data.table 中计算总和的每个变量的聚合

r - ggplot直方图颜色渐变

r - ggplotly : log argument cancels axis labels

r - ggplot2 - 多图缩放

r - 设置文档持久化 ggplot2 颜色主题

r - ggplot2 中标签文本条目中的不同字体和大小