我需要為一個專案繪制一棵漂亮的樹。問題是我必須使用特定的函式來創建創建樹資料型別的樹,并且所有用于以很好的方式繪制樹的函式(ggtree、rpart.plot)都需要其他型別的物件。您能否幫我更改樹的物件資料型別或建議我使用其他函式來繪制它們?我必須密謀prune.result。我不能使用其他函式來創建和修剪樹。(我知道我可以使用plotsimple 函式,但我在所有專案中都使用 ggplot 包,所以我想要類似的東西)。
先感謝您
dataframe <- data_frame(y = as.factor(rbinom(1000, size = 1, prob = 0.3)), x0 = rnorm(1000), x1 = rnorm(1000, 3), x2 = rnorm(1000, 3,0.5), x3 = rnorm(1000, 1,0.5), x4 = rnorm(1000, 3.5), x5 = rnorm(1000, 2.3,0.5), x6 = rnorm(1000, 1,0.5), x7 = as.factor(rbinom(1000, size = 4, prob = 0.5)), x8 = as.factor(rbinom(1000, size = 3, prob = 0.8)))
library(tree)
tree = tree::tree(y ~., data=dataframe, split='gini', control = tree.control(nobs=dim(dataframe)[1],mincut=1,minsize=2))
prune.result = prune.misclass(tree, best =12)
我嘗試將 prune.result 轉換為資料框以將其用于 ggtree,并且我還嘗試將其轉換為 rpart 物件,但我沒有管理。
uj5u.com熱心網友回復:
如果你需要使用tree包生成的樹物件,但你想要 ggplot 輸出,你應該檢查ggdendro
這是基于您的示例的完整代表:
set.seed(1)
dataframe <- data.frame(y = as.factor(rbinom(1000, size = 1, prob = 0.3)),
x0 = rnorm(1000),
x1 = rnorm(1000, 3),
x2 = rnorm(1000, 3,0.5),
x3 = rnorm(1000, 1,0.5),
x4 = rnorm(1000, 3.5),
x5 = rnorm(1000, 2.3,0.5),
x6 = rnorm(1000, 1,0.5),
x7 = as.factor(rbinom(1000, size = 4, prob = 0.5)),
x8 = as.factor(rbinom(1000, size = 3, prob = 0.8)))
library(tree)
library(ggdendro)
tree <- tree(y ~ ., data = dataframe, split = 'gini',
control = tree.control(nobs = nrow(dataframe),
mincut = 1, minsize = 2))
prune.result <- prune.misclass(tree, best = 12)
ggdendrogram(prune.result, theme_dendro = FALSE)

由reprex 包創建于 2022-03-28 (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451540.html
