![](/img/trans.png)
[英]How to get `geom_smooth()` to understand the formula in result of `lm()`?
[英]Custom lm formula in geom_smooth
我正在使用多面圖,並在geom_smooth()
使用lm
方法添加線條
d<-data.frame(n=c(100, 80, 60, 55, 50, 102, 78, 61, 42, 18),
year=rep(2000:2004, 2),
cat=rep(c("a", "b"), each=5))
ggplot(d, aes(year, n, group=cat))+geom_line()+geom_point()+
facet_wrap(~cat, ncol=1)+
geom_smooth(method="lm")
我想設置一個函數來適當地應用多項式。 我已經完成了一個功能:
lm.mod<-function(df){
m1<-lm(n~year, data=df)
m2<-lm(n~year+I(year^2), data=df)
ifelse(AIC(m1)<AIC(m2), "y~x", "y~poly(x, 2)")
}
但是我在應用它時遇到了麻煩。 任何想法,或更好的方法來解決這個問題?
使用單個geom_smooth
調用不可能應用不同的平滑函數。 這是一個基於平滑數據子集的解決方案:
首先,創建沒有geom_smooth
的基礎圖:
library(ggplot2)
p <- ggplot(d, aes(year, n, group = cat)) +
geom_line() +
geom_point() +
facet_wrap( ~ cat, ncol = 1)
第二,該函數by
用於創建一個geom_smooth
的每個水平cat
(用於磨制的變量)。 此函數返回一個列表。
p_smooth <- by(d, d$cat,
function(x) geom_smooth(data=x, method = lm, formula = lm.mod(x)))
現在,您可以將geom_smooth
列表添加到基礎圖中:
p + p_smooth
該圖包括上面板的二階多項式和下面板的線性光滑:
lm.mod<-function(df){
m1<-lm(n~year, data=df)
m2<-lm(n~year+I(year^2), data=df)
p <- ifelse(AIC(m1)<AIC(m2), "y~x", "y~poly(x, 2)")
return(p)
}
# I only made the return here explicit out of personal preference
ggplot(d, aes(year, n, group=cat)) + geom_line() + geom_point() +
facet_wrap(~cat, ncol=1)+
stat_smooth(method=lm, formula=lm.mod(d))
# stat_smooth and move of your function to formula=
# test by reversing the condition and you should get a polynomial.
# lm.mod<-function(df){
# m1<-lm(n~year, data=df)
# m2<-lm(n~year+I(year^2), data=df)
# p <- ifelse(AIC(m1)>AIC(m2), "y~x", "y~poly(x, 2)")
# return(p)
# }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.