r - 如何在 ggplot2 对象的每个面上放置相同的平滑?

标签 r plot ggplot2 facet

下面是一个例子:

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)

谢谢你的帮助!

安德鲁

最佳答案

妙招:setting the faceting variable to 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)

关于r - 如何在 ggplot2 对象的每个面上放置相同的平滑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673074/

相关文章:

r - Pander+Knitr : Error when using pander. 列表问题

matlab - 如何压制数字?

r - 手动颜色和条件填充而不覆盖geom_point中的position_dodge?

r - ggplot2构面标签中的表达式

r - 如何 reshape 数据框以生成两列值(R 编程)

r - 从点到原点的 ggplot 线和余弦分数

r - 更改圆环图中标签的位置

python - python中函数的自适应绘图

graph - GnuPlot中的线图,其中线色是数据文件中的第三列?

r - 添加图例条目使所有其他图例条目成为对角线和矩形