4

这是一个例子:

eg <- data.frame(x = c(1:50, 50:1),  
                 y = c(1:50, 1:50) + rnorm(100),  
                 g = rep(c("a","b"), each=50))  

qplot(x, y, data = eg) +  
  facet_wrap(~ g) +  
  geom_smooth()  

我希望能够在两个方面绘制整体平滑度以及具有特定于方面的平滑度。

编辑:这是一种方法。

my.smooth <- gam(y ~ s(x), data = eg)
my.data <- data.frame(x = 1:50)                                           
my.data$y <- predict(my.smooth, newdata = my.data) 

qplot(x, y, data = eg) + 
    facet_wrap(~ g) + 
    geom_smooth() + 
    geom_smooth(data = my.data)

谢谢你的帮助!

安德鲁

4

1 回答 1

6

巧妙的技巧:将 faceting 变量设置为 NULL

library(ggplot2)
eg <- data.frame(x = c(1:50, 50:1),  
                 y = c(1:50, 1:50) + rnorm(100),  
                 g = rep(c("a","b"), each=50))  

p <- qplot(x, y, data = eg) +  
  facet_wrap(~ g) +  
  geom_smooth()

p + geom_smooth(data=within(eg, g <- NULL), fill="red")

或者,如果您愿意,请使用facet_grid(..., margins=TRUE)

p + facet_grid(.~g, margins=TRUE)
于 2011-12-02T10:12:08.927 回答