我正在使用多面图,并使用中的lm
方法添加线geom_smooth()
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
该图包括上面板的二阶多项式和下面板的线性平滑:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句