I'm trying to plot just a set of beta coefficients in a beta solution path plot with R. Here are the beta values that I'm trying to plot:
s0
AtBat .
Hits 1.136258490
HmRun .
Runs .
RBI .
Walks 1.182645827
Years .
CAtBat .
CHits .
CHmRun .
CRuns 0.110122200
CRBI 0.314564189
CWalks .
LeagueN .
DivisionW .
PutOuts 0.003304879
Assists .
Errors .
NewLeagueN .
The type of plot that I want to get from this set of betas is:
And here is the code with which I'm trying to plot the betas:
tmp <- as.data.frame(as.matrix(beta))
tmp$coef <- row.names(tmp)
tmp <- reshape::melt(tmp, id = "coef")
tmp$norm <- apply(abs(beta[-1,]), 2, sum)[tmp$variable+1] # compute L1 norm
When I run the code above I get an error from tmp$norm
: Error in apply(abs(beta[-1, ]), 2, sum) :
dim(X) must have a positive length
Then I want to plot the betas with the code below which I cannot run because I don't get a tmp$norm
value:
ggplot(tmp[tmp$coef != "(Intercept)",], aes(norm, value, color = coef, linetype = coef)) +
geom_line() +
xlab("L1 norm") +
guides(color = guide_legend(title = ""),
linetype = guide_legend(title = "")) +
theme_bw() +
theme(legend.key.width = unit(3,"lines"))
Here is a simple beta reproducible code, to get some values of beta:
beta=matrix(sample(1:19),19,1)
The number of samples and predictors can be any arbitrary number, like number of samples n=200 and predictors =19.