Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding labels on curves in glmnet plot in R

Tags:

plot

r

glmnet

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.

like image 428
rnso Avatar asked May 31 '15 17:05

rnso


1 Answers

An alternative is the plot_glmnet function in the plotmo package. It automatically positions the variable names and has a few other bells and whistles. For example, the following code

library(glmnet)
mod <- glmnet(as.matrix(mtcars[-1]), mtcars[,1])
library(plotmo) # for plot_glmnet
plot_glmnet(mod)

gives

plot

The variable names are spread out to prevent overplotting, but we can still make out which curve is associated with which variable. Further examples may be found in Chapter 6 in plotres vignette which is included in the plotmo package.

like image 145
Stephen Milborrow Avatar answered Sep 21 '22 07:09

Stephen Milborrow