重要图:
我想将y轴文本对齐,并且还想根据不同的变量组对变量着色。例如Limonene和Valencane,a-Selinene和g-Selinen属于同一群体。
但我在“randomForest”包中找不到任何用于自定义绘图的代码。你对定制有什么建议吗?谢谢!
这里有一个工作示例:
您需要创建所需的分组,然后将ggplot
与geom_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()