LASSO回归构建完成后,可以使用plot(fit)来绘制LASSO图。但我想使用 ggplot 重新绘制该图并美化它。我使用下面的代码重新绘制,但是重新绘制的LASSO图和plot(fit)绘制的图不一致。 x轴间隔和plot(fit)不同,线条也不完全相同。有什么问题? 另外,如何在重绘的ggplot图表中添加一个辅助x轴(x轴)来显示变量的数量,类似于plot(fit)? 我的代码如下:
library(glmnet)
library(dplyr)
library(ggplot2)
x <- matrix(rnorm(100 * 20), 100, 20)
y <- sample(1:2, 100, replace = TRUE)
fit <- glmnet(x, y, family = "binomial")
# Original graph
plot(fit2, xvar = "lambda", label = T)
tidied <- broom::tidy(fit) %>% filter(term!= "(Intercept)")
# Redraw with ggplot
ggplot(tidied, aes(lambda, estimate, group = term, color = term)) +
geom_line() +
scale_x_log10()
为了开始使用,您应该认识到您需要自然对数,而不是 log10。
tidied <- broom::tidy(fit) %>% filter(term!= "(Intercept)") %>%
mutate(lnlambda = log(lambda))
然后您可以生成这样的 ggplot 版本:
# Redraw with ggplot
min_lambda = min(tidied$lnlambda)
ggplot(tidied, aes(lnlambda, estimate, group = term, color = term)) +
geom_line() +
geom_text(data = slice_min(tidied, lnlambda, by=term),
aes(label=substr(term,2, length(term)), color=term, x=min_lambda, y=estimate),
nudge_x =-.1, size=2
) +
geom_text(data = slice_min(
data.frame(df = fit$df, lambda=fit$lambda) %>% filter(df %in% c(20,19,17,13,6)),
lambda,
by=df),
aes(label=df,x=log(lambda), y=0.5),inherit.aes = FALSE
) +
scale_y_continuous(breaks= seq(-.4,.4, .2)) +
theme(legend.position = "none") +
labs(x = "Log Lambda", y="Coefficients")
注意:您的示例不可重现,因为您在采样之前没有
set.seed()
。这也意味着我的解决方案中的一些硬编码值需要调整。其中包括:
filter(df %in% c(...))
y=0.5
)scale_y_continuous