在R中的glmnet图中的曲线上添加标签 [英] Adding labels on curves in glmnet plot in R

查看:381
本文介绍了在R中的glmnet图中的曲线上添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用glmnet软件包从mtcars数据集中获取以下图表(其他变量的mpg回归):

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')

如何在每条曲线的开始处或在其最大y点(距x轴最大距离)处为每个曲线添加变量名称?我尝试过,可以像往常一样添加图例,但不能在每条曲线上或其开始处添加标签.感谢您的帮助.

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.

推荐答案

由于标签是硬编码的,因此编写快速功能可能更容易.这只是一个快速的快照,因此可以进行更彻底的更改.我还要注意,使用套索时,通常会有很多变量,因此标签会有很多重叠(如您的小示例所示)

As the labels are hard coded it is perhaps easier to write a quick function. This is just a quick shot, so can be changed to be more thorough. I would also note that when using the lasso there are normally a lot of variables so there will be a lot of overlap of the labels (as seen in your small example)

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, ...)
}

# plot
plot(fit, xvar="lambda")

# label
lbs_fun(fit)

这篇关于在R中的glmnet图中的曲线上添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆