我使用rpart训练了一个模型,我想生成一个图,显示它用于决策树的变量的变量重要性,但我不知道如何生成。
我能够提取变量重要性。我尝试过ggplot,但没有显示任何信息。我尝试对它使用plot()函数,但它只给出了一个平面图。我也尝试了plot.default,它稍微好一点,但仍然是我想要的。
下面是rpart模型训练:
argIDCART = rpart(Argument ~ .,
data = trainSparse,
method = "class")将变量重要性放入数据框中。
argPlot <- as.data.frame(argIDCART$variable.importance)下面是它打印的内容的一部分:
argIDCART$variable.importance
noth 23.339346
humanitarian 16.584430
council 13.140252
law 11.347241
presid 11.231916
treati 9.945111
support 8.670958我想画一张图,显示变量/功能名称及其数字重要性。我就是不能让它这么做。它似乎只有一列。我试着用分离函数把它们分开,但也做不到。
ggplot(argPlot, aes(x = "variable importance", y = "feature"))只打印空白。
其他的情节看起来真的很糟糕。
plot.default(argPlot)看起来像是绘制点,但没有放入变量名。
发布于 2019-05-25 23:19:59
由于没有可重复使用的示例,因此我使用ggplot2包和其他用于数据操作的包,基于自己的R数据集安装了我的响应。
library(rpart)
library(tidyverse)
fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
df <- data.frame(imp = fit$variable.importance)
df2 <- df %>%
tibble::rownames_to_column() %>%
dplyr::rename("variable" = rowname) %>%
dplyr::arrange(imp) %>%
dplyr::mutate(variable = forcats::fct_inorder(variable))
ggplot2::ggplot(df2) +
geom_col(aes(x = variable, y = imp),
col = "black", show.legend = F) +
coord_flip() +
scale_fill_grey() +
theme_bw()

ggplot2::ggplot(df2) +
geom_segment(aes(x = variable, y = 0, xend = variable, yend = imp),
size = 1.5, alpha = 0.7) +
geom_point(aes(x = variable, y = imp, col = variable),
size = 4, show.legend = F) +
coord_flip() +
theme_bw()

发布于 2019-05-25 20:23:33
如果您想要查看变量名称,最好将它们用作x轴上的标签。
plot(argIDCART$variable.importance, xlab="variable",
ylab="Importance", xaxt = "n", pch=20)
axis(1, at=1:7, labels=row.names(argIDCART))

(可能需要调整窗口大小才能正确查看标签。)
如果您有许多变量,您可能希望轮换变量名称,以便不会重叠。
par(mar=c(7,4,3,2))
plot(argIDCART$variable.importance, xlab="variable",
ylab="Importance", xaxt = "n", pch=20)
axis(1, at=1:7, labels=row.names(argIDCART), las=2)

数据
argIDCART = read.table(text="variable.importance
noth 23.339346
humanitarian 16.584430
council 13.140252
law 11.347241
presid 11.231916
treati 9.945111
support 8.670958",
header=TRUE)https://stackoverflow.com/questions/56304698
复制相似问题