How can I show a polynomial of degree of different degree in ggplot2 with facet_grid?

I want to use edges (because I like the way they look for it) to show polynomial approaches of increasing degree. It's easy enough to break them apart separately like this:

df <- data.frame(x=rep(1:10,each=10),y=rnorm(100))

ggplot(df,aes(x=x,y=y)) + stat_smooth(method="lm",formula=y~poly(x,2))
ggplot(df,aes(x=x,y=y)) + stat_smooth(method="lm",formula=y~poly(x,3))
ggplot(df,aes(x=x,y=y)) + stat_smooth(method="lm",formula=y~poly(x,4))

      

I know I can always combine them using rodents, but I would like to combine them using facet_grid

if possible. Perhaps something similar to:

poly2 <- df
poly2$degree <- 2
poly3 <- df
poly3$degree <- 3
poly4 <- df
poly4$degree <- 4
polyn <- rbind(poly2,poly3,poly4)

ggplot(polyn,aes(x=x,y=y)) + stat_smooth(method="lm",formula=y~poly(x,degree)) +
  facet_grid(degree~.)

      

This does not work, of course, because the cut does not work for y~poly(x,degree)

, therefore it degree

is extracted from the data. Is there a way to make this work?

+3


source to share


2 answers


You can always predict points manually and then easily remove a face,

## Data
set.seed(0)
df <- data.frame(x=rep(1:10,each=10),y=rnorm(100))

## Get poly fits
dat <- do.call(rbind, lapply(1:4, function(d)
    data.frame(x=(x=runif(1000,0,10)),
               y=predict(lm(y ~ poly(x, d), data=df), newdata=data.frame(x=x)),
               degree=d)))

ggplot(dat, aes(x, y)) +
  geom_point(data=df, aes(x, y), alpha=0.3) +
  geom_line(color="steelblue", lwd=1.1) +
  facet_grid(~ degree)

      

enter image description here



To add confidence ranges, you can use the interval='confidence'

c option predict

. You may also be interested in a function ggplot2::fortify

to get more relevant statistics.

dat <- do.call(rbind, lapply(1:4, function(d) {
    x <- seq(0, 10, len=100)
    preds <- predict(lm(y ~ poly(x, d), data=df), newdata=data.frame(x=x), interval="confidence")
    data.frame(cbind(preds, x=x, degree=d))
}))

ggplot(dat, aes(x, fit)) +
  geom_point(data=df, aes(x, y), alpha=0.3) +
  geom_line(color="steelblue", lwd=1.1) +
  geom_ribbon(aes(x=x, ymin=lwr, ymax=upr), alpha=0.3) +
  facet_grid(~ degree)

      

enter image description here

+4


source


I have a very ugly solution where the facet is faceted and the fits are plotted for the respective subsets of the data:

p1 <- ggplot(polyn,aes(x=x,y=y)) + facet_grid(.~degree)
p1  +
  stat_smooth(data=polyn[polyn$degree==2,],formula=y~poly(x,2),method="lm") +
  stat_smooth(data=polyn[polyn$degree==3,],formula=y~poly(x,3),method="lm") +
  stat_smooth(data=polyn[polyn$degree==4,],formula=y~poly(x,4),method="lm")

      



gives enter image description here

+2


source







All Articles