geom_smooth with facet_grid and different fitting functions

前端 未结 1 518
梦谈多话
梦谈多话 2020-12-19 09:00

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

1条回答
  •  死守一世寂寞
    2020-12-19 09:34

    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)
    

    0 讨论(0)
提交回复
热议问题