geom_smooth中的自定义lm公式 [英] Custom lm formula in geom_smooth
问题描述
我正在处理多面图,并在geom_smooth()
I'm working with faceted plots, and adding lines using the lm
method in 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")
我想设置一个函数以在适当的情况下应用多项式.我已经设计了一个功能:
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?
推荐答案
不可能通过单个geom_smooth
调用来应用不同的平滑函数.这是一个基于数据子集平滑的解决方案:
It's not possible to apply different smooth functions with a single geom_smooth
call. Here is a solution which is based on smoothing subsets of data:
首先,创建不带geom_smooth
的基础图:
First, create the base plot without geom_smooth
:
library(ggplot2)
p <- ggplot(d, aes(year, n, group = cat)) +
geom_line() +
geom_point() +
facet_wrap( ~ cat, ncol = 1)
第二,功能by
用于为cat
的每个级别(用于构面的变量)创建geom_smooth
.此函数返回一个列表.
Second, the function by
is used to create a geom_smooth
for each level of cat
(the variable used for facetting). This function returns a list.
p_smooth <- by(d, d$cat,
function(x) geom_smooth(data=x, method = lm, formula = lm.mod(x)))
现在,您可以将geom_smooth
的列表添加到基本图中:
Now, you can add the list of geom_smooth
s to your base plot:
p + p_smooth
该图包括上面板的二阶多项式和下面板的线性平滑:
The plot includes a second-order polynomial for the upper panel and a linear smooth for the lower panel:
这篇关于geom_smooth中的自定义lm公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!