0

我试图通过以下演示来感受 ggraph 包:https ://www.r-bloggers.com/plotting-trees-from-random-forest-models-with-ggraph/ 。

我想将边缘类型更改为肘形并尝试替换geom_edge_link()为,geom_edge_elbow()但这会返回错误“FUN 中的错误(X[[i]],...):找不到对象'方向'”。

查阅手册,我猜这是因为对象“图形”属于 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]],...):找不到对象'方向'。

4

0 回答 0