Debian Codegraph @

R/dendro_tree.R

raw
1 #
2 # ggdendro/R/dendro_tree.R by Andrie de Vries Copyright (C) 2011-2015
3 # Contains code from tree/R/tree.R by B. D. Ripley Copyright (C) 1994-2015
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 or 3 of the License
8 # (at your option).
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18 #
19
20
21 # tree_ggdendro_env <- new.env()
22
23 #' Extract data from regression tree object for plotting using ggplot.
24 #'
25 #' Extracts data to plot line segments and labels from a `tree::tree()` object.
26 #' This data can then be manipulated or plotted, e.g. using [ggplot2::ggplot()].
27 #'
28 #' @param model object of class "tree", e.g. the output of tree()
29 #'
30 #' @param type Either `proportional` or `uniform`. If this partially matches
31 #' "uniform", the branches are of uniform length. Otherwise they are
32 #' proportional to the decrease in impurity.
33 #'
34 #' @param ... ignored
35 #'
36 #' @export
37 #'
38 #' @return
39 #' A list of three data frames:
40 #' \item{segments}{a data frame containing the line segment data}
41 #' \item{labels}{a data frame containing the label text data}
42 #' \item{leaf_labels}{a data frame containing the leaf label text data}
43 #'
44 #' @seealso [ggdendrogram()]
45 #' @family dendro_data methods
46 #' @family tree functions
47 #' @author Andrie de Vries, using code modified from original by Brian Ripley
48 #' @example inst/examples/example_dendro_tree.R
49 dendro_data.tree <- function(model, type = c("proportional", "uniform"), ...) {
50 type <- match.arg(type)
51 uniform <- type == "uniform"
52
53 # dev <- dev.cur()
54 # if (dev == 1L) dev <- 2L # as device will be opened.
55
56 # assign(paste0("device", dev), uniform, envir = tree_ggdendro_env)
57
58 labels <- tree_labels(model, uniform = uniform, ...)
59 as.dendro(
60 segments = tree_segments(model, uniform, ...),
61 labels = labels$labels,
62 leaf_labels = labels$leaf_labels,
63 class = "tree"
64 )
65 }
66
67
68
69 #' Extract data frame from tree object for plotting using ggplot.
70 #' @param model object of class "tree", e.g. the output of tree()
71 #' @param ... ignored
72 #' @keywords internal
73 #' @seealso [ggdendrogram()]
74 #' @family tree functions
75 #' @author Code modified from original by Brian Ripley
76 tree_segments <- function(model, uniform, ...) {
77 if (missing(uniform)) stop("specify the uniform argument")
78 # Uses tree:::treeco to extract data frame of plot locations
79 xy <- treeco(model, uniform = uniform)
80 n <- model$frame$n
81
82 # Lines copied from tree:::treepl
83 x <- xy$x
84 y <- xy$y
85 node <- as.numeric(row.names(model$frame))
86 parent <- match((node %/% 2), node)
87 sibling <- match(ifelse(node %% 2, node - 1L, node + 1L), node)
88
89 linev <- data.frame(x = x, y = y, xend = x, yend = y[parent], n = n)
90 lineh <- data.frame(x = x[parent], y = y[parent], xend = x, yend = y[parent],
91 n = n)
92
93 rbind(linev[-1, ], lineh[-1, ])
94 }
95
96 #' Extract labels data frame from tree object for plotting using ggplot.
97 #' @param model object of class "tree", e.g. the output of tree()
98 #' @param ... ignored
99 #' @return a list with two elements: $labels and $leaf_labels
100 #' @keywords internal
101 #' @seealso [ggdendrogram()]
102 #' @family tree functions
103 #' @author Code modified from original by Brian Ripley
104 tree_labels <- function(model, uniform, ...) {
105 # Uses tree:::treeco to extract data frame of plot locations
106 xy <- treeco(model, uniform = uniform)
107 label <- model$frame$var
108 yval <- model$frame$yval
109 sleft <- model$frame$splits.cutleft
110 sright <- model$frame$splits.right
111
112 # Lines copied from tree:::treepl
113 x <- xy$x
114 y <- xy$y
115 node <- as.numeric(row.names(model$frame))
116 parent <- match((node %/% 2), node)
117 sibling <- match(ifelse(node %% 2, node - 1L, node + 1L), node)
118
119 # Extract labels
120 data <- data.frame(x = x, y = y, label = label)
121 data <- data[data$label != "<leaf>", ]
122 labels <- as.data.frame(data)
123
124 # Extract leaf labels
125 data <- data.frame(x, y, label, yval)
126 data <- data[data$label == "<leaf>", ]
127 if (is.numeric(data$yval)) {
128 data$label <- round(data$yval, 2)
129 } else {
130 data$label <- data$yval
131 }
132 leaf_labels <- as.data.frame(data)
133
134 list(
135 labels = labels,
136 leaf_labels = leaf_labels
137 )
138 }
139
140 #' Extract labels data frame from tree object for plotting using ggplot.
141 #'
142 #' Extract labels data frame from tree object for plotting using ggplot
143 #'
144 #' @param model object of class "tree", e.g. the output of tree()
145 #' @param ... ignored
146 #' @keywords internal
147 #' @seealso [ggdendrogram()]
148 #' @family tree functions
149 #' @author Code modified from original by Brian Ripley
150 get_data_tree_leaf_labels <- function(model, uniform, ...) {
151 # Uses tree:::treeco to extract data frame of plot locations
152 xy <- treeco(model, uniform = uniform)
153 label <- model$frame$var
154 yval <- model$frame$yval
155 sleft <- model$frame$splits.cutleft
156 sright <- model$frame$splits.right
157
158 # Lines copied from tree:::treepl
159 x <- xy$x
160 y <- xy$y
161 node <- as.numeric(row.names(model$frame))
162 parent <- match((node %/% 2), node)
163 sibling <- match(ifelse(node %% 2, node - 1L, node + 1L), node)
164
165 data <- data.frame(x, y, label, yval)
166 data <- data[data$label == "<leaf>", ]
167 data$label <- round(data$yval, 2)
168 data
169 }
170
171
172 # treeco ------------------------------------------------------------------
173
174 #' Function copied from tree:::treeco.
175 #'
176 #' @param tree tree object
177 #' @param uniform ???
178 #' @keywords internal
179 treeco <- function(tree, uniform) {
180 # if (missing(uniform)) {
181 # pn <- paste0("device", dev.cur())
182 # uniform <- if (exists(pn, envir = tree_ggdendro_env, inherits = FALSE))
183 # get(pn, envir = tree_ggdendro_env, inherits = FALSE)
184 # else FALSE
185 # }
186 if (missing(uniform)) stop("specify uniform argument")
187
188 frame <- tree$frame
189 node <- as.integer(row.names(frame))
190 depth <- tree.depth(node)
191 x <- -depth
192 if (uniform) {
193 y <- x
194 } else {
195 y <- dev <- frame$dev
196 depth <- split(seq(node), depth)
197 parent <- match(node %/% 2L, node)
198 sibling <- match(
199 ifelse(node %% 2L, node - 1L, node + 1L),
200 node
201 )
202 for (i in depth[-1L]) {
203 y[i] <- y[parent[i]] - dev[parent[i]] +
204 dev[i] + dev[sibling[i]]
205 }
206 }
207 depth <- -x
208 leaves <- frame$var == "<leaf>"
209 x[leaves] <- seq(sum(leaves))
210 depth <- split(seq(node)[!leaves], depth[!leaves])
211 left.child <- match(node * 2L, node)
212 right.child <- match(node * 2 + 1L, node)
213 for (i in rev(depth)) x[i] <- 0.5 * (x[left.child[i]] + x[right.child[i]])
214 list(x = x, y = y)
215 }