代码之家  ›  专栏  ›  技术社区  ›  Dan

具有镶嵌网格和不同拟合函数的geom\u平滑

  •  7
  • Dan  · 技术社区  · 7 年前

    首先,我为这个例子道歉,但我找不到更好的数据集来证明这个问题。希望它足够了。比如说,我正试图制作一个变速器的平面网格(自动与手动)和齿轮数 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 .

    1 回复  |  直到 7 年前
        1
  •  4
  •   Marco Sandri    7 年前

    遵循给出的建议 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