Adding labels on curves in glmnet plot in R

后端 未结 3 850
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 12:36

I am using glmnet package to get following graph from mtcars dataset (regression of mpg on other variables):

library(glmnet)
fit = glmnet(as.matrix(mtcars[-1         


        
3条回答
  •  不思量自难忘°
    2020-12-06 13:32

    As the labels are hard coded it is perhaps easier to write a quick function. This is just a quick shot, so can be changed to be more thorough. I would also note that when using the lasso there are normally a lot of variables so there will be a lot of overlap of the labels (as seen in your small example)

    lbs_fun <- function(fit, ...) {
            L <- length(fit$lambda)
            x <- log(fit$lambda[L])
            y <- fit$beta[, L]
            labs <- names(y)
            text(x, y, labels=labs, ...)
    }
    
    # plot
    plot(fit, xvar="lambda")
    
    # label
    lbs_fun(fit)
    

    enter image description here

提交回复
热议问题