File: geom_conn_bundle.R

package info (click to toggle)
r-cran-ggraph 2.2.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,832 kB
  • sloc: cpp: 1,630; makefile: 2
file content (224 lines) | stat: -rw-r--r-- 7,655 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#' Create hierarchical edge bundles between node connections
#'
#' Hierarchical edge bundling is a technique to introduce some order into the
#' hairball structure that can appear when there's a lot of overplotting and
#' edge crossing in a network plot. The concept requires that the network has
#' an intrinsic hierarchical structure that defines the layout but is not shown.
#' Connections between points (that is, not edges) are then drawn so that they
#' loosely follows the underlying hierarchical structure. This results in a
#' flow-like structure where lines that partly move in the same direction will
#' be bundled together.
#'
#' @note In order to avoid excessive typing edge aesthetic names are
#' automatically expanded. Because of this it is not necessary to write
#' `edge_colour` within the `aes()` call as `colour` will
#' automatically be renamed appropriately.
#'
#' @section Aesthetics:
#' geom_conn_bundle* understands the following aesthetics. Bold aesthetics are
#' automatically set, but can be overwritten.
#' \itemize{
#'  \item{\strong{x}}
#'  \item{\strong{y}}
#'  \item{\strong{group}}
#'  \item{\strong{circular}}
#'  \item{edge_colour}
#'  \item{edge_width}
#'  \item{edge_linetype}
#'  \item{edge_alpha}
#'  \item{filter}
#' }
#'
#' @section Computed variables:
#'
#' \describe{
#'  \item{index}{The position along the path (not computed for the *0 version)}
#' }
#'
#'
#' @inheritParams geom_edge_link
#' @inheritParams ggplot2::geom_path
#'
#' @param data The result of a call to [get_con()]
#'
#' @param tension How "loose" should the bundles be. 1 will give very tight
#' bundles, while 0 will turn of bundling completely and give straight lines.
#' Defaults to 0.8
#'
#' @author Thomas Lin Pedersen
#'
#' @family geom_conn_*
#'
#' @references
#' Holten, D. (2006). *Hierarchical edge bundles: visualization
#' of adjacency relations in hierarchical data.* IEEE Transactions on
#' Visualization and Computer Graphics, **12**(5), 741-748.
#' \doi{10.1109/TVCG.2006.147}
#'
#' @examples
#' # Create a graph of the flare class system
#' library(tidygraph)
#' flareGraph <- tbl_graph(flare$vertices, flare$edges) %>%
#'   mutate(
#'     class = map_bfs_chr(node_is_root(), .f = function(node, dist, path, ...) {
#'       if (dist <= 1) {
#'         return(shortName[node])
#'       }
#'       path$result[[nrow(path)]]
#'     })
#'   )
#' importFrom <- match(flare$imports$from, flare$vertices$name)
#' importTo <- match(flare$imports$to, flare$vertices$name)
#'
#' # Use class inheritance for layout but plot class imports as bundles
#' ggraph(flareGraph, 'dendrogram', circular = TRUE) +
#'   geom_conn_bundle(aes(colour = after_stat(index)),
#'     data = get_con(importFrom, importTo),
#'     edge_alpha = 0.25
#'   ) +
#'   geom_node_point(aes(filter = leaf, colour = class)) +
#'   scale_edge_colour_distiller('', direction = 1, guide = 'edge_direction') +
#'   coord_fixed() +
#'   ggforce::theme_no_axes()
#' @rdname geom_conn_bundle
#' @name geom_conn_bundle
#'
NULL

#' @rdname ggraph-extensions
#' @format NULL
#' @usage NULL
#' @importFrom ggforce StatBspline
#' @export
StatConnBundle <- ggproto('StatConnBundle', StatBspline,
  setup_data = function(data, params) {
    data <- StatFilter$setup_data(data, params)
    if (nrow(data) == 0) return(data)
    relax(data, params$tension)
  },
  setup_params = function(data, params) {
    if (is.null(params$tension)) {
      params$tension <- 0.8
    }
    if (params$tension < 0) params$tension <- 0
    if (params$tension > 1) params$tension <- 1
    params
  },
  required_aes = c('x', 'y'),
  default_aes = aes(filter = TRUE),
  extra_params = c('na.rm', 'n', 'tension', 'type')
)
#' @rdname geom_conn_bundle
#'
#' @export
geom_conn_bundle <- function(mapping = NULL, data = get_con(),
                             position = 'identity', arrow = NULL,
                             lineend = 'butt', show.legend = NA,
                             n = 100, tension = 0.8, ...) {
  mapping <- complete_edge_aes(mapping)
  mapping <- aes_intersect(mapping, aes(x = x, y = y,
                                        group = con.id))
  layer(
    data = data, mapping = mapping, stat = StatConnBundle,
    geom = GeomEdgePath, position = position, show.legend = show.legend,
    inherit.aes = FALSE,
    params = expand_edge_aes(
      list2(
        arrow = arrow, lineend = lineend, n = n, interpolate = FALSE,
        tension = tension, type = 'clamped', ...
      )
    )
  )
}
#' @rdname ggraph-extensions
#' @format NULL
#' @usage NULL
#' @importFrom ggforce StatBspline2
#' @export
StatConnBundle2 <- ggproto('StatConnBundle2', StatBspline2,
  setup_data = function(data, params) {
    StatConnBundle$setup_data(data, params)
  },
  setup_params = function(data, params) {
    StatConnBundle$setup_params(data, params)
  },
  required_aes = c('x', 'y'),
  default_aes = aes(filter = TRUE),
  extra_params = c('na.rm', 'n', 'tension', 'type')
)
#' @rdname geom_conn_bundle
#'
#' @export
geom_conn_bundle2 <- function(mapping = NULL, data = get_con(),
                              position = 'identity', arrow = NULL,
                              lineend = 'butt', show.legend = NA,
                              n = 100, tension = 0.8, ...) {
  mapping <- complete_edge_aes(mapping)
  mapping <- aes_intersect(mapping, aes(x = x, y = y,
                                        group = con.id))
  layer(
    data = data, mapping = mapping, stat = StatConnBundle2,
    geom = GeomEdgePath, position = position, show.legend = show.legend,
    inherit.aes = FALSE,
    params = expand_edge_aes(
      list(
        arrow = arrow, lineend = lineend, n = n, interpolate = TRUE,
        tension = tension, type = 'clamped', ...
      )
    )
  )
}
#' @rdname ggraph-extensions
#' @format NULL
#' @usage NULL
#' @export
StatConnBundle0 <- ggproto('StatConnBundle0', StatIdentity,
  setup_data = function(data, params) {
    StatConnBundle$setup_data(data, params)
  },
  setup_params = function(data, params) {
    StatConnBundle$setup_params(data, params)
  },
  required_aes = c('x', 'y'),
  default_aes = aes(filter = TRUE),
  extra_params = c('na.rm', 'n', 'tension', 'type')
)
#' @rdname geom_conn_bundle
#'
#' @export
geom_conn_bundle0 <- function(mapping = NULL, data = get_con(),
                              position = 'identity', arrow = NULL,
                              lineend = 'butt', show.legend = NA,
                              tension = 0.8, ...) {
  mapping <- complete_edge_aes(mapping)
  mapping <- aes_intersect(mapping, aes(x = x, y = y,
                                        group = con.id))
  layer(
    data = data, mapping = mapping, stat = StatConnBundle0,
    geom = GeomEdgeBspline, position = position, show.legend = show.legend,
    inherit.aes = FALSE,
    params = expand_edge_aes(
      list2(
        arrow = arrow, lineend = lineend, tension = tension, type = 'clamped',
        ...
      )
    )
  )
}
#' @importFrom utils head tail
relax <- function(data, strength) {
  formula <- function(p, startInd, endInd, pathLengths) {
    start <- rep(p[startInd], pathLengths)
    range <- rep(p[endInd] - p[startInd], pathLengths)
    ind <- unlist(lapply(pathLengths, seq_len)) - 1
    length <- rep(pathLengths, pathLengths)
    strength * p + (1 - strength) * (start + (ind / (length - 1)) * range)
  }
  idInds <- split(seq_len(nrow(data)), data$group)
  pathLengths <- lengths(idInds)
  startInd <- vapply(idInds, head, integer(1), n = 1)
  endInd <- vapply(idInds, tail, integer(1), n = 1)
  data$x <- formula(data$x, startInd, endInd, pathLengths)
  data$y <- formula(data$y, startInd, endInd, pathLengths)
  data
}