I used a dataset to fit three kinds of models, and applied a decomposition to calculate feature importance of each variable. I want to visualize the results like the example below to draw a comparison across three models. Is it possible to draw a stacked bar plot with given y and decomposition results?
ggplot(data = diamonds)
geom_bar(mapping = aes(x = cut, fill = clarity))
Here is an example of my data:
tibble(
methods = c("linear regression", "decision tree", "random forest"),
y = c(1, 2, 3),
g1 = c(0.3, 0.8, 1.3),
g2 = c(0.5, 1, 1),
g3 = c(0.2, 0.2, 0.7)
)
# A tibble: 3 × 5
methods y g1 g2 g3
<chr> <dbl> <dbl> <dbl> <dbl>
1 linear regression 1 0.3 0.5 0.2
2 decision tree 2 0.8 1 0.2
3 random forest 3 1.3 1 0.7
CodePudding user response:
You can do it with the melt
function from reshape2
package to melt your tibble into a format in which each row is a unique id-variable entry:
library(reshape2);
library(ggplot2);
df_melt <- melt(df, id.vars = 'methods')
ggplot(df_melt, aes(x=methods, y=value, fill=variable)) geom_bar(position="fill", stat="identity")