[英]Custom lm formula in geom_smooth
I'm working with faceted plots, and adding lines using the lm
method 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")
I would like to set up a function to apply a polynomial where appropriate. 我想设置一个函数来适当地应用多项式。 I've worked up a function:
我已经完成了一个功能:
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)")
}
But I'm having trouble applying it. 但是我在应用它时遇到了麻烦。 Any ideas, or better ways to approach this?
任何想法,或更好的方法来解决这个问题?
It's not possible to apply different smooth functions with a single geom_smooth
call. 使用单个
geom_smooth
调用不可能应用不同的平滑函数。 Here is a solution which is based on smoothing subsets of data: 这是一个基于平滑数据子集的解决方案:
First, create the base plot without geom_smooth
: 首先,创建没有
geom_smooth
的基础图:
library(ggplot2)
p <- ggplot(d, aes(year, n, group = cat)) +
geom_line() +
geom_point() +
facet_wrap( ~ cat, ncol = 1)
Second, the function by
is used to create a geom_smooth
for each level of cat
(the variable used for facetting). 第二,该函数
by
用于创建一个geom_smooth
的每个水平cat
(用于磨制的变量)。 This function returns a list. 此函数返回一个列表。
p_smooth <- by(d, d$cat,
function(x) geom_smooth(data=x, method = lm, formula = lm.mod(x)))
Now, you can add the list of geom_smooth
s to your base plot: 现在,您可以将
geom_smooth
列表添加到基础图中:
p + p_smooth
The plot includes a second-order polynomial for the upper panel and a linear smooth for the lower panel: 该图包括上面板的二阶多项式和下面板的线性光滑:
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.