使用Ranger函数计算的绘制特征重要性。

8
我需要使用ranger函数来绘制变量重要性,因为我有一个大的数据表,并且在我的研究案例中randomForest无法工作。
这是我的代码:
library(ranger)
set.seed(42)
model_rf <- ranger(Sales ~ .,data = data[,-1],importance = "impurity")

然后我创建了一个新的数据框DF,它包含了上面代码中的内容,如下所示

> v<-as.vector(model_rf$variable.importance$Importance)
> w<-(as.vector((row.names(df))))
> DF<-cbind(w,v)
> DF<-as.data.frame(DF)
> DF
                           w                v
1                  DayOfWeek 376393213095.426
2                  Customers 1364058809531.96
3                       Open 634528877741.021
4                      Promo 261749509069.205
5               StateHoliday 5196666310.34041
6              SchoolHoliday  6522969049.3763
7                   DateYear  7035399071.0376
8                  DateMonth 20134820116.2625
9                    DateDay 37631766745.2306
10                  DateWeek 32834962167.9479
11                 StoreType 31568433413.5718
12                Assortment 20257406597.8358
13       CompetitionDistance  111847579772.77
14 CompetitionOpenSinceMonth 46332196019.0118
15  CompetitionOpenSinceYear 45548903472.6485
16                    Promo2                0
17           Promo2SinceWeek 50666744628.7906
18           Promo2SinceYear 40964066303.0407
19           CompetitionOpen 39927447341.0351
20                 PromoOpen  28319356095.063
21            IspromoinSales 2844220121.08598

但是根据上面显示的结果,我需要绘制这样一个图形:

enter image description here

编辑

正如@Sam所建议的,我尝试着调整了这段代码:

> ggplot(DF, aes(x=reorder(w,v), y=v,fill=v))+ 
+   geom_bar(stat="identity", position="dodge")+ coord_flip()+
+   ylab("Variable Importance")+
+   xlab("")+
+   ggtitle("Information Value Summary")+
+   guides(fill=F)+
+   scale_fill_gradient(low="red", high="blue")

但我收到了这个错误:

错误:在连续比例尺中提供了离散值。此外:有42个警告(使用warnings()查看)>

请问我该如何解决这个问题呢?谢谢!

请将您的数据框以我们可以直接读取的格式粘贴。例如 https://pastebin.com/ - Sam
@Axeman,这是来自 library(ranger) 的内容。 - Rprogrammer
类似这样的 ggplot(stack(model_rf$variable.impotance), aes(ind, values)) + geom_col() + coord_flip() - Axeman
@Axeman,不,它不起作用。 - Rprogrammer
@Sam,请查看已编辑的问题。 - Rprogrammer
1个回答

9
这个还没有经过测试,但我认为这应该能满足你的需求。
ggplot(
    enframe(
        model_rf$variable.importance,
        name = "variable",
        value = "importance"
    ),
    aes(
        x = reorder(variable, importance),
        y = importance,
        fill = importance
    )
) +
    geom_bar(stat = "identity", position = "dodge") +
    coord_flip() +
    ylab("Variable Importance") +
    xlab("") +
    ggtitle("Information Value Summary") +
    guides(fill = "none") +
    scale_fill_gradient(low = "red", high = "blue")
  

它为何无法工作?你收到了哪个错误?请编辑您原来的答案,向我展示您尝试调整代码的方式以及您收到的错误信息。 - Sam
展示一个 str(DF)。看起来你的某个变量是因子类型。 - Sam
尝试将类别为字符的“变量”创建出来。并且数字应该是类型为“numeric”,而不是类型为“Factor”。DF$v <- as.numeric(DF$v) - Sam
尝试先从ggplot代码中删除guides(),看看是否可以解决问题。 - Sam
1
哦,谢谢!最终当我删除“guides”时它可以工作了。 - Rprogrammer
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接