Debian Codegraph @

R/dendro_rpart.R

raw
1 #
2 # ggdendro/R/dendro_rpart.R by Andrie de Vries Copyright (C) 2011-2015
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 or 3 of the License
7 # (at your option).
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # A copy of the GNU General Public License is available at
15 # http://www.r-project.org/Licenses/
16 #
17 # Classification Tree with rpart
18
19
20 #' Extract data from classification tree object for plotting using ggplot.
21 #'
22 #' Extracts data to plot line segments and labels from a
23 #' [rpart::rpart()] classification tree object. This data can then be
24 #' manipulated or plotted, e.g. using [ggplot2::ggplot()].
25 #'
26 #' This code is in essence a copy of [rpart::plot.rpart()], retaining
27 #' the plot data but without plotting to a plot device.
28 #'
29 #' @param model object of class "tree", e.g. the output of tree()
30 #'
31 #' @param uniform if TRUE, uniform vertical spacing of the nodes is used; this
32 #' may be less cluttered when fitting a large plot onto a page. The default is
33 #' to use a non-uniform spacing proportional to the error in the fit.
34 #'
35 #' @param branch controls the shape of the branches from parent to child node.
36 #' Any number from 0 to 1 is allowed. A value of 1 gives square shouldered
37 #' branches, a value of 0 give V shaped branches, with other values being
38 #' intermediate.
39 #'
40 #' @param compress if FALSE, the leaf nodes will be at the horizontal plot
41 #' coordinates of 1:nleaves. If TRUE, the routine attempts a more compact
42 #' arrangement of the tree. The compaction algorithm assumes uniform=TRUE;
43 #' surprisingly, the result is usually an improvement even when that is not
44 #' the case.
45 #'
46 #' @param nspace the amount of extra space between a node with children and a
47 #' leaf, as compared to the minimal space between leaves. Applies to
48 #' compressed trees only. The default is the value of branch.
49 #'
50 #' @param minbranch set the minimum length for a branch to minbranch times the
51 #' average branch length. This parameter is ignored if uniform=TRUE. Sometimes
52 #' a split will give very little improvement, or even (in the classification
53 #' case) no improvement at all. A tree with branch lengths strictly
54 #' proportional to improvement leaves no room to squeeze in node labels.
55 #'
56 #' @param ... ignored
57 #' @export
58 #' @return
59 #' A list of three data frames:
60 #' \item{segments}{a data frame containing the line segment data}
61 #' \item{labels}{a data frame containing the label text data}
62 #' \item{leaf_labels}{a data frame containing the leaf label text data}
63 #'
64 #' @seealso [ggdendrogram()]
65 #' @family dendro_data methods
66 #' @family rpart functions
67 #' @example inst/examples/example_dendro_rpart.R
68 #'
69 dendro_data.rpart <- function(model, uniform = FALSE, branch = 1, compress = FALSE,
70 nspace, minbranch = 0.3, ...) {
71 x <- model
72 if (!inherits(x, "rpart")) stop("Not a legitimate \"rpart\" object")
73 if (nrow(x$frame) <= 1L) stop("fit is not a tree, just a root")
74
75 if (compress & missing(nspace)) nspace <- branch
76 if (!compress) nspace <- -1L # means no compression
77 # if(!interactive()) if (dev.cur() == 1L) dev.new() # not needed in R
78
79 parms <- list(
80 uniform = uniform,
81 branch = branch,
82 nspace = nspace,
83 minbranch = minbranch
84 )
85
86 ## define the plot region
87 temp <- rpartco(x, parms = parms)
88 xx <- temp$x
89 yy <- temp$y
90 # temp1 <- range(xx) + diff(range(xx)) * c(-margin, margin)
91 # temp2 <- range(yy) + diff(range(yy)) * c(-margin, margin)
92 # plot(temp1, temp2, type = "n", axes = FALSE, xlab = "", ylab = "", ...)
93 ## Save information per device, once a new device is opened.
94 # assign(paste0("device", dev.cur()), parms, envir = rpart_ggdendro_env)
95
96 # Draw a series of horseshoes or V's, left son, up, down to right son
97 # NA's in the vector cause lines() to "lift the pen"
98 node <- as.numeric(row.names(x$frame))
99 temp <- rpart.branch(xx, yy, node, branch)
100
101 # if (branch > 0) text(xx[1L], yy[1L], "|")
102 # lines(c(temp$x), c(temp$y))
103 # invisible(list(x = xx, y = yy))
104
105 labels <- text_rpart(x, parms = parms)
106
107 segments <- rpart_segments(temp)
108 # labels <- rpart_labels(xx, ...)
109 as.dendro(
110 segments = segments,
111 labels = labels$labels,
112 leaf_labels = labels$leaf_labels,
113 class = "rpart"
114 )
115 }
116
117 #' Extract data frame from rpart object for plotting using ggplot.
118 #' @param ... ignored
119 #' @keywords internal
120 #' @seealso [ggdendrogram()]
121 #' @family rpart functions
122 rpart_segments <- function(x, ...) {
123 dat <- data.frame(
124 stack(as.data.frame(x$x)),
125 stack(as.data.frame(x$y))
126 )[, c("ind", "values", "values.1")]
127
128 dat <- cbind(head(dat, -1), tail(dat, -1))
129 dat <- dat[complete.cases(dat), -4]
130 names(dat) <- c("n", "x", "y", "xend", "yend")
131 dat
132 }
133
134
135 #' Extract labels data frame from rpart object for plotting using ggplot.
136 #'
137 #' This code is modified from the original plot.rpart in package rpart.
138 #' @return a list with two elements: $labels and $leaf_labels
139 #' @author Original author Brian Ripley
140 #' @keywords internal
141 #' @seealso [ggdendrogram()]
142 #' @family dendro_data methods
143 #' @family rpart functions
144 rpart_labels <- function(x) {
145 labelSplits <- labelLeaves <- NULL
146 list(
147 labels = labelSplits,
148 leaf_labels = labelLeaves
149 )
150 }