First, the libraries
library(tidyr)
library(leaps)
library(ggplots2)
library(ggdark)
The value of the model
set.seed(1)
X = rnorm(100)
e = rnorm(100)
Y = 8 + 7*X + 2.5*X^2 - 9*X^3 + e
Fitting
data.all = data.frame(Y,X)
regfit.full = regsubsets(Y~poly(X,10,raw=T), data=data.all, nvmax=10)
(reg.summary = summary(regfit.full))
Then I get the minimum value for each variables
(reg.min.cp = which.min(reg.summary$cp))
(reg.min.bic = which.min(reg.summary$bic))
(reg.min.adjr2 = which.min(reg.summary$adjr2))
Creating the data frame for plot
df = data.frame(reg.summary$cp, reg.summary$bic, reg.summary$adjr2)
df$rownum = 1:nrow(df)
Reshaping the data frame
molten = df %>% gather(variable, value, reg.summary.cp:reg.summary.adjr2 )
Plotting with facets
(lp = molten %>% ggplot(data=.) +
aes(x=rownum, y=value) +
geom_line(col="black") +
geom_point(data=molten, aes(xint=reg.min.adjr2, z="reg.summary.adjr2", col="red")) + # this is where I got the wrong plot
facet_wrap(~variable, scales="free_y")
)
And it shows wrong. What I expect is that the geom_point(data=molten, aes(xint=reg.min.adjr2, z="reg.summary.adjr2", col="red"))
will just add the reg.min.adjr2
to the facet reg.summary.adjr2
and only one point.
How to make it in that way?