Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

r - How do I place an identical smooth on each facet of a ggplot2 object?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...