如何在ggplot2对象的每个面上放置相同的平滑图形? [英] How do I place an identical smooth on each facet of a ggplot2 object?

查看:131
本文介绍了如何在ggplot2对象的每个面上放置相同的平滑图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子:

 例如<  -  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< - 预测(my。 smooth,newdata = my.data)

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

感谢您的帮助!

Andrew

解决方案

将faceting变量设置为NULL

<$ p (x = c(1:50,50:1),
y = c(1:50,1)的数据库(ggplot2)
例如< :50)+ rnorm(100),
g = rep(c(a,b),each = 50))

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

p + geom_smo oth(数据=在(例如,g < - NULL),fill =red)内

或者,如果您愿意,可以使用 facet_grid(...,margin = TRUE)

  p + facet_grid(。〜g,margin = TRUE)


Here's an example:

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

I'd like to be able to plot the overall smooth on both facets as well as having the facet-specific smooths.

Edit: here's one way.

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)

Thanks for any help!

Andrew

解决方案

Clever trick: 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")

Or if you prefer, use facet_grid(..., margins=TRUE):

p + facet_grid(.~g, margins=TRUE)

这篇关于如何在ggplot2对象的每个面上放置相同的平滑图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆