我修改了这篇文章中的函数(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)
然而,我在剧情和传奇中的文字标签之间不匹配。变量'am'显然是错误的颜色。错误在哪里?谢谢你的帮助。
答案 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
}
答案 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)