Search code examples
rggplot2plotregressionglmnet

Plotting cross validation of ridge regression's MSE


first of all, I have to apologize for my poor English. Second, the objective of this post is that I want to reproduce the plot of the ridge regression's MSE with ggplot2 instead of the function plot which is included in R.

The object of cv.out is defined by the next expression: cv.out <- cv.glmnet(x_var[train,], y_var[train], alpha = 0). And when I print that object these are the elements of cv.out

Lambda Measure SE Nonzero
min 439.8 32554969 1044541 5
lse 1343.1 33586547 1068662 5

This is the plot with plot(cv.out):

Image of the plot

The thing what I want to do the same plot but more elaborated with ggplot and I don't know which aesthetics put in the function. These are the elements of cv.out when I call the object like this: cv.out$ :

  • lambda
  • cmv
  • cvsd
  • cvup
  • cvlo
  • nzero
  • call
  • name
  • lambda.min
  • lambda.lse

Finally, thanks for your help. I really appreciate it. :)


Solution

  • Using example dataset:

    X = as.matrix(mtcars[,-1])
    y = as.matrix(mtcars[,1])
    cv.out = cv.glmnet(X,y,alpha=0)
    plot(cv.out)
    

    enter image description here

    You just need to pull out the values and put into a data.frame, and plot using geom_point() and geom_errorbar() :

    df = with(cv.out,
         data.frame(lambda = lambda,MSE = cvm,MSEhi=cvup,MSElow=cvlo))
    
    ggplot(df,aes(x=lambda,y=MSE)) + 
    geom_point(col="#f05454") + 
    scale_x_log10("log(lambda)") + 
    geom_errorbar(aes(ymin = MSElow,ymax=MSEhi),col="#30475e") + 
    geom_vline(xintercept=c(cv.out$lambda.1se,cv.out$lambda.min),
    linetype="dashed")+
    theme_bw()
    

    enter image description here