【问题标题】:How to customize the Importance Plot generated by package "randomForest"如何自定义包“randomForest”生成的重要性图
【发布时间】:2019-02-11 11:34:52
【问题描述】:

重要性图:

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

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

【问题讨论】:

  • 首先它被称为“重要性图”。可以做到,但您需要使用从varImp() 调用中获得的原始数据。
  • 谢谢。但是我怎样才能使用我的原始数据呢?添加变量“组”信息或?

标签: r random-forest


【解决方案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)。

根据 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()

【讨论】:

  • 谢谢。这看起来像使用提取的重要变量通过 ggplot 创建一个新图。但我实际上想直接自定义重要性图。这是一个目标人物,我希望我的人物是“nature.com/articles/srep25948/figures/7”。你知道如何管理它吗?
  • 我向您展示了一种方法,您可以通过使用我给您的东西来改变它。例如geom_bar 可以是geom_point
  • 重点是您可以创建一个 data.frame 并使用它,varImpPlot 函数无法进行简单的自定义。
  • 非常感谢。我会试试的。
  • 更新了我的答案。
猜你喜欢
  • 2020-05-12
  • 2012-07-28
  • 2019-04-17
  • 2020-08-12
  • 2015-07-25
  • 2021-08-22
  • 2018-09-12
  • 2017-12-23
  • 2011-05-08
相关资源
最近更新 更多