通过以下演示,我试图对ggraph包有所了解:https://www.r-bloggers.com/plotting-trees-from-random-forest-models-with-ggraph/。
我想将边缘类型更改为弯头,并尝试将geom_edge_link()
替换为geom_edge_elbow()
,但这会返回错误“错误在FUN(X [[i]],...)中:找不到对象“方向””。
咨询manual时,我猜测这是因为对象“图形”属于igraph类,而不是树状图,但是我不确定,并且想知道是否有人可以提出解决方法?
以下是上面链接中演示应用到mtcars数据集的代码:
library(randomForest)
library(igraph)
library(ggplot2)
library(ggraph)
data(mtcars)
mtcars_rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000)
# get tree by index
tree <- randomForest::getTree(mtcars_rf,
k = 100,
labelVar = TRUE) %>%
tibble::rownames_to_column() %>%
# make leaf split points to NA, so the 0s won't get plotted
mutate(`split point` = ifelse(is.na(prediction), `split point`, NA))
# prepare data frame for graph
graph_frame <- data.frame(from = rep(tree$rowname, 2),
to = c(tree$`left daughter`, tree$`right daughter`))
# convert to graph and delete the last node that we don't want to plot
graph <- graph_from_data_frame(graph_frame) %>%
delete_vertices("0")
# set node labels
V(graph)$node_label <- gsub("_", " ", as.character(tree$`split var`))
V(graph)$leaf_label <- as.character(tree$prediction)
V(graph)$split <- as.character(round(tree$`split point`, digits = 2))
dendro <- as.dendrogram(graph)
# plot
plot <- ggraph(graph, layout = 'dendrogram') +
theme_bw() +
geom_edge_elbow() +
geom_node_point() +
geom_node_text(aes(label = node_label), na.rm = TRUE, repel = TRUE) +
geom_node_label(aes(label = split), vjust = 2.5, na.rm = TRUE, fill = "white") +
geom_node_label(aes(label = leaf_label, fill = leaf_label), na.rm = TRUE,
repel = TRUE, colour = "white", fontface = "bold", show.legend = FALSE)
print(plot)
运行此命令将引发错误:“ FUN(X [[i]],...)中的错误:找不到对象'方向'”。