带有facet_grid和不同拟合函数的geom_smooth [英] geom_smooth with facet_grid and different fitting functions

查看:193
本文介绍了带有facet_grid和不同拟合函数的geom_smooth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,为这个例子道歉,但我找不到一个更好的数据集来证明这个问题。希望这足以。假设我正在试图从传输(自动与手动)和 mtcars 数据集中的齿轮数量进行比较,这些数据将mpg与位移进行比较,如下所示:

 #加载库
库(ggplot2)

#加载数据
数据(mtcars)

#绘图数据
p < - ggplot(mtcars,aes(x = disp,y = mpg))+ geom_point()+ facet_grid(gear〜am)
p <-p + geom_smooth()
print(p)

/ p>



注意,我添加了趋势线使用 geom_smooth ,并默认使用黄土曲线。我可以使用用户定义的函数而不是黄土曲线,使用 nls 作为方法,然后陈述一个公式,这很好。但是,是否有可能为每个方面拟合不同的用户指定的曲线?例如,左上方的线性回归和右下方的指数衰减。这可能吗?还是我用锤子来驱动螺丝?

编辑
为自定义(即用户定义的)拟合函数提供解决方案


First of all, apologies for the example, but I couldn't find a better data set to demonstrate the problem. Hopefully, it will suffice. Say I'm trying to make a facet grid of transmission (automatic vs. manual) and number of gears from the mtcars data set that plots mpg against displacement, like this:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth()
print(p)

which gives,

Notice, I've added a trend line using geom_smooth and it has defaulted to use a loess curve. I can fit user-defined functions rather than a loess curve using nls for the method and then stating a formula, which is great. But is it possible to fit different user-specified curves for each facet? For example, a linear regression to the top left panel and decaying exponential for the bottom right. Is this possible? Or am I using a hammer to drive in screws?

EDIT: A solution for custom (i.e., user-defined) fitting functions is given here.

解决方案

Following the suggestions given here, a possibile solution is:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Vector of smoothing methods for each plot panel
meths <- c("loess","lm","lm","lm","lm","lm","lm")

# Smoothing function with different behaviour in the different plot panels
mysmooth <- function(formula,data,...){
   meth <- eval(parse(text=meths[unique(data$PANEL)]))
   x <- match.call()
   x[[1]] <- meth
   eval.parent(x)
}

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="mysmooth")
print(p)

这篇关于带有facet_grid和不同拟合函数的geom_smooth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆