rnso rnso - 11 days ago 5
R Question

Adding labels on curves in glmnet plot in R

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]), mtcars[,1])
plot(fit, xvar='lambda')


enter image description here

How can I add names of variables to each curve, either at beginning of each curve or at its maximal y point (maximum away from x-axis)? I tried and I can add legend as usual but not labels on each curve or at its start. Thanks for your help.

Answer

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