gpt4 book ai didi

r - geom_smooth 与 facet_grid 和不同的拟合函数

转载 作者:行者123 更新时间:2023-12-01 00:25:55 24 4
gpt4 key购买 nike

首先,为这个例子道歉,但我找不到更好的数据集来证明这个问题。希望,它就足够了。假设我正在尝试从 mtcars 制作变速器(自动与手动)和齿轮数量的分面网格绘制 mpg 与位移的数据集,如下所示:

# 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)

这使,

enter image description here

请注意,我使用 geom_smooth 添加了一条趋势线。它默认使用黄土曲线。我可以使用 nls 拟合用户定义的函数而不是黄土曲线对于方法,然后陈述一个公式,这很棒。但是有没有可能适合 不同 每个方面的用户指定曲线?例如,左上角的线性回归和右下角的衰减指数。这可能吗?还是我用锤子打螺丝?

编辑 :
给出了自定义(即用户定义)拟合函数的解决方案 here .

最佳答案

按照给出的建议here ,一个可能的解决方案是:

# 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)

enter image description here

关于r - geom_smooth 与 facet_grid 和不同的拟合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com