After the LASSO regression is constructed, plot(fit) can be employed to plot the LASSO graph. But I want to redraw this graph using ggplot and beautify it. I use the following code to redraw it, but the redrawn LASSO graph and the graph drawn by plot(fit) are inconsistent. The x-axis interval and the plot(fit) are different, and the lines are not exactly the same. What's the problem? In addition, how to add a secondary x-axis (x-axis) to the redrawn ggplot graph to display the number of variables, similar to the plot(fit)? My code is as follows:
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()
