/
vizSurfaceShape.R
198 lines (161 loc) · 6.64 KB
/
vizSurfaceShape.R
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
## TODO: provide examples for adjusting legend size / spacing
#' @title Visual Summary of Surface Shape
#'
#' @description A unique display of surface shape (typically curvature) probability, suitable for across-slope or down-slope shape. Use the `title` argument to make this clear.
#'
#' @param x \code{data.frame} as created by \code{soilDB::fetchOSD(..., extended=TRUE)}, see details
#'
#' @param s an optional soil series name, highlighted in the figure
#'
#' @param title a reasonable title for the figure
#'
#' @param annotations logical, add number of record and normalized Shannon entropy values
#'
#' @param annotation.cex annotation label scaling factor
#'
#' @param cols vector of colors
#'
#' @param \dots additional arguments to `[iterateHydOrder]`: `target = 0.9, maxIter = 20, j.amount = 0.05, verbose = FALSE`
#'
#' @return
#' A `list` with the following elements:
#' * `fig`: lattice object (the figure)
#' * `order`: 1D ordering from `cluster::diana`
#' * `clust`: `hclust` object
#' * `match.rate`: fraction of series matching target hydrologic ordering, after clustering + rotation
#'
#' @details See the \href{http://ncss-tech.github.io/AQP/soilDB/soil-series-query-functions.html}{Soil Series Query Functions} tutorial for more information.
#'
#' @author D.E. Beaudette
#'
#'
vizSurfaceShape <- function(x, title = 'Surface Shape', s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#2B83BA", "#FFFFBF", "#D7191C", "#808080", "darkgreen"), ...) {
# sanity checks on input
if(!inherits(x, 'data.frame')) {
stop('x must be a data.frame', call. = FALSE)
}
if(nrow(x) < 1) {
stop('x must contain at least 1 row of data', call. = FALSE)
}
# check for required packages
if(!requireNamespace('dendextend', quietly=TRUE) | !requireNamespace('latticeExtra', quietly=TRUE))
stop('please install the `dendextend` and `latticeExtra` packages', call.=FALSE)
# CRAN CHECK hack
surface_shape <- NULL
# save row names as they are lost in the distance matrix calc
row.names(x) <- x$series
# save number of records
n.records <- x$n
# number of series
n.series <- nrow(x)
# save normalized Shannon entropy
H <- x$shannon_entropy
# mask-out some columns we don't need
x$n <- NULL
x$shannon_entropy <- NULL
## convert proportions to long format for plotting
x.long <- melt(x, id.vars = 'series')
# fix names: second column contains labels
names(x.long)[2] <- 'surface_shape'
# make some colors, and set style
# cols <- rev(brewer.pal(5, 'Spectral'))
# cols <- c(cols[c(1, 3, 5)], grey(0.5), 'darkgreen')
# colorspace::swatchplot(cols)
# setup plot styling
tps <- list(superpose.polygon = list(col = cols, lwd = 2, lend = 2))
## all of the fancy ordering + dendrogram require > 1 series
if(n.series > 1) {
# iteratively apply hydrologic ordering,
.res <- iterateHydOrder(x, g = 'shape', ...)
x.d.hydro <- .res$clust
.match.rate <- .res$match.rate
# re-order labels levels based on clustering
x.long$series <- factor(x.long$series, levels = x$series[x.d.hydro$order])
# dendrogram synced to bars
leg <- list(
right = list(
fun = latticeExtra::dendrogramGrob,
args = list(
x = as.dendrogram(x.d.hydro),
side = "right",
size = 10)
)
)
} else {
# singleton
x.long$series <- factor(x.long$series)
# no dendrogram legend
leg <- list()
# simulate output from clustering
x.d.hydro <- list(order = 1L)
.match.rate <- NA
}
# hack to ensure that simpleKey works as expected
suppressWarnings(trellis.par.set(tps))
# must manually create a key, for some reason auto.key doesn't work with fancy dendrogram
sk <- simpleKey(space='top', columns=5, text=levels(x.long$surface_shape), rectangles = TRUE, points=FALSE, between.columns=2, between=1, cex=0.75)
# a single series can be highlighted via argument 's'
## TODO: check for missing / mis-specified series names
pp <- barchart(series ~ value, groups = surface_shape, data=x.long, horiz=TRUE, stack=TRUE,
xlab = 'Proportion',
main = title,
scales = list(cex=1),
key = sk,
legend = leg,
panel = function(...) {
panel.barchart(...)
if(annotations) {
# annotation coords
x.pos.N <- unit(0.03, 'npc')
x.pos.H <- unit(0.97, 'npc')
y.pos <- unit((1:nrow(x)) - 0.25, 'native')
y.pos.annotation <- unit(nrow(x) + 0.25, 'native')
# annotate with number of records
grid.text(
as.character(n.records[x.d.hydro$order]),
x = x.pos.N,
y = y.pos,
gp = gpar(cex = annotation.cex, font = 1)
)
# annotate with H
grid.text(
as.character(round(H[x.d.hydro$order], 2)),
x = x.pos.H,
y = y.pos,
gp = gpar(cex = annotation.cex, font = 3)
)
# annotation labels
grid.text(
c('N', 'H'),
x = c(x.pos.N, x.pos.H),
y = y.pos.annotation,
gp = gpar(cex = annotation.cex, font = c(2, 4))
)
}
},
yscale.components=function(..., s.to.bold=s) {
temp <- yscale.components.default(...)
if(!is.null(s.to.bold)) {
temp$left$labels$labels <-
sapply( temp$left$labels$labels,
function(x) {
if(grepl(s.to.bold, x, ignore.case = TRUE)) {
as.expression(bquote( bold(.(x))))
} else {
as.expression(bquote(.(x)))
}
}
)
}
return(temp)
})
# embed styling
pp <- update(pp, par.settings = tps)
# re-pack results
res <- list(
fig = pp,
order = x.d.hydro$order,
clust = x.d.hydro,
match.rate = .match.rate
)
}