Legend label errors with glmnet plot in R

那年仲夏 提交于 2019-12-10 18:44:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!