0

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

enter image description here

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?

isemaj
  • 557
  • 1
  • 6
  • 19

1 Answers1

0

I got some idea here from these two SO:

How to add different lines for facets

Add a segment only to one facet using ggplot2

What I did is to create first a new data frame for the min values for cp , bic, and adjr2. And then add the points to the main plot.

I make sure that the value for x will be the rownum and the y are the min values. I also added a parameter variable to min_plot to make sure that it will be added to the right facet.

min_plot = data.frame(
  rownum=c(reg.min.cp, reg.min.bic, reg.min.adjr2),
  y = c(reg.summary$cp[reg.min.cp], reg.summary$bic[reg.min.bic], reg.summary$adjr2[reg.min.adjr2]),
  variable=c("reg.summary.cp", "reg.summary.bic", "reg.summary.adjr2"))

(lp = molten %>% ggplot(data=.) 
  + aes(x=rownum, y=value)  
  + geom_line(col="black")  
  + facet_wrap(~variable, scales="free_y")  
  + geom_point(data = min_plot, aes(x=rownum, y=y), col="red")
)
isemaj
  • 557
  • 1
  • 6
  • 19