如何自定义包“randomForest”生成的重要性图

问题描述 投票:0回答:1

重要图:

enter image description here

我想将y轴文本对齐,并且还想根据不同的变量组对变量着色。例如Limonene和Valencane,a-Selinene和g-Selinen属于同一群体。

但我在“randomForest”包中找不到任何用于自定义绘图的代码。你对定制有什么建议吗?谢谢!

r random-forest
1个回答
1
投票

这里有一个工作示例:

您需要创建所需的分组,然后将ggplotgeom_bar一起使用。

set.seed(4543)
data(mtcars)

library(randomForest)
mtcars.rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
                          importance=TRUE)
imp <- varImpPlot(mtcars.rf) # let's save the varImp object

# this part just creates the data.frame for the plot part
library(dplyr)
imp <- as.data.frame(imp)
imp$varnames <- rownames(imp) # row names to column
rownames(imp) <- NULL  
imp$var_categ <- rep(1:2, 5) # random var category

# this is the plot part, be sure to use reorder with the correct measure name
library(ggplot2) 
ggplot(imp, aes(x=reorder(varnames, IncNodePurity), weight=IncNodePurity, fill=as.factor(var_categ))) + 
  geom_bar() +
  scale_fill_discrete(name="Variable Group") +
  ylab("IncNodePurity") +
  xlab("Variable Name")

您可以对其他重要性测量执行相同操作,只需相应地更改绘图部分(weight = %IncMSE)。

enter image description here

根据OP回答更新:

ggplot(imp, aes(x=reorder(varnames, IncNodePurity), y=IncNodePurity, color=as.factor(var_categ))) + 
  geom_point() +
  geom_segment(aes(x=varnames,xend=varnames,y=0,yend=IncNodePurity)) +
  scale_color_discrete(name="Variable Group") +
  ylab("IncNodePurity") +
  xlab("Variable Name") +
  coord_flip()

enter image description here

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.