[英]ggplot2 - plot multiple models on the same plot
我有一個線性和非線性模型的列表,這些模型是從不同的數據集派生而來的,這些數據集測量的兩個變量x
和y
是我想使用stat_smooth
在同一圖上stat_smooth
。 這樣可以輕松比較整個數據集之間x
和y
之間關系的形狀。
我正在嘗試找出最有效的方法。 現在,我正在考慮創建一個空的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)
編輯:請注意,此答案發布后,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))
這將產生:
我認為,這里的答案是得到一個想要運行的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.