R中glmnet图的图例标签错误

时间:2015-06-01 06:15:54

标签: r plot glmnet

我修改了这篇文章中的函数(Adding labels on curves in glmnet plot in R),将图例添加到图中,如下所示:

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)

enter image description here

然而,我在剧情和传奇中的文字标签之间不匹配。变量'am'显然是错误的颜色。错误在哪里?谢谢你的帮助。

2 个答案:

答案 0 :(得分:4)

plot(fit, xvar="lambda")使用函数matplot。默认情况下,matplot使用6种颜色并对其进行回收。因此,您必须相应地创建图例:

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
}

enter image description here

答案 1 :(得分:1)

您可以在plot来电中指定颜色,以匹配您为传奇选择的颜色:

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)

enter image description here