问题
I modified the function from this post ( Adding labels on curves in glmnet plot in R ) to add legend to the plot as follows:
library(glmnet)
fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1])
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, ...)
legend('topright', legend=labs, col=1:length(labs), lty=1) # <<< ADDED BY ME
}
plot(fit, xvar="lambda")
lbs_fun(fit)

However, I am getting mismatch between text labels on plot and in legend. The variable 'am' is clearly incorrectly colored. Where is the error? Thanks for your help.
回答1:
plot(fit, xvar="lambda")
utilizes the function matplot
. By default, matplot
uses 6 colors and recycles them. So you have to create the legend accordingly:
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, ...)
legend('topright', legend=labs, col=1:6, lty=1) # only 6 colors
}

回答2:
You can specify the colors in the plot
call to match the colors you've picked for the legend:
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, ...)
legend('topright', legend=labs, col=1:length(labs), lty=1) # <<< ADDED BY ME
}
plot(fit, xvar="lambda", col=1:dim(coef(fit))[1])
lbs_fun(fit)

来源:https://stackoverflow.com/questions/30566788/legend-label-errors-with-glmnet-plot-in-r