-
Notifications
You must be signed in to change notification settings - Fork 8
/
scales_coltab.R
233 lines (206 loc) · 5.56 KB
/
scales_coltab.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
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
225
226
227
228
229
230
231
232
233
#' Discrete scales based in the color table of a `SpatRaster`
#'
#' @description
#'
#' Some categorical `SpatRaster` objects may have an associated color table.
#' This function extract those values. These functions generates scales and
#' vector of colors based on the color table [terra::coltab()] associated to a
#' `SpatRaster`.
#'
#' You can also get a vector of colors named with the corresponding
#' factor with [get_coltab_pal()].
#'
#' Additional parameters `...` would be passed on to
#' [ggplot2::discrete_scale()].
#'
#' **Note that** \CRANpkg{tidyterra} just documents a selection of these
#' additional parameters, check [ggplot2::discrete_scale()] to see the full
#' range of parameters accepted.
#'
#' @export
#'
#' @name scale_coltab
#' @rdname scale_coltab
#'
#' @inheritDotParams ggplot2::discrete_scale breaks:drop
#'
#' @inheritParams scale_cross_blended
#'
#' @param data,x A `SpatRaster` with one or several color tables.
#' See [terra::has.colors()].
#'
#' @seealso [terra::coltab()], [ggplot2::discrete_scale()],
#' [ggplot2::scale_fill_manual()],
#'
#' @return
#' The corresponding \CRANpkg{ggplot2} layer with the values applied to the
#' `fill/colour` aesthetics.
#'
#' @examples
#' library(terra)
#' # Geological Eras
#' # Spanish Geological Survey (IGME)
#'
#' r <- rast(system.file("extdata/cyl_era.tif", package = "tidyterra"))
#'
#' plot(r)
#'
#' # Get coltab
#' coltab_pal <- get_coltab_pal(r)
#'
#' coltab_pal
#'
#' \donttest{
#' # With ggplot2 + tidyterra
#' library(ggplot2)
#'
#' gg <- ggplot() +
#' geom_spatraster(data = r)
#'
#'
#' # Default plot
#' gg
#'
#' # With coltabs
#' gg +
#' scale_fill_coltab(data = r)
#' }
scale_fill_coltab <- function(data, ..., alpha = 1,
na.translate = FALSE,
na.value = "transparent",
drop = TRUE) {
getcols <- get_coltab_pal(data)
if (is.null(getcols)) {
return(ggplot2::geom_blank())
}
if (alpha < 0 || alpha > 1) {
cli::cli_abort("{.arg alpha} {.field {alpha}} not in {.field [0,1]}")
}
getcols <- ggplot2::alpha(getcols, alpha = alpha)
if (isTRUE(na.translate)) {
# Unname
getcols <- unname(getcols)
}
ggplot2::scale_fill_manual(...,
values = getcols,
na.translate = na.translate,
na.value = na.value,
drop = drop
)
}
#' @rdname scale_coltab
#' @export
scale_colour_coltab <- function(data, ..., alpha = 1, na.translate = FALSE,
na.value = "transparent", drop = TRUE) {
getcols <- get_coltab_pal(data)
if (is.null(getcols)) {
return(ggplot2::geom_blank())
}
if (alpha < 0 || alpha > 1) {
cli::cli_abort("{.arg alpha} {.field {alpha}} not in {.field [0,1]}")
}
getcols <- ggplot2::alpha(getcols, alpha = alpha)
if (isTRUE(na.translate)) {
# Unname
getcols <- unname(getcols)
}
ggplot2::scale_colour_manual(...,
values = getcols,
na.translate = na.translate,
na.value = na.value,
drop = drop
)
}
#' @export
#' @rdname scale_wiki
#' @usage NULL
scale_color_coltab <- scale_colour_coltab
#' @rdname scale_coltab
#' @export
get_coltab_pal <- function(x) {
if (!inherits(x, "SpatRaster")) {
cli::cli_alert_info(
paste(
"{.fun tidyterra::get_coltab_pal} only works with",
"{.cls SpatRaster} objects, not {.cls {class(x)}}.",
"Returning {.field NULL}"
)
)
return(NULL)
}
if (!any(terra::has.colors(x))) {
cli::cli_alert_info(
"{.arg x} does not have a color table. Returning {.field NULL}",
)
return(NULL)
}
# Complete layers with no coltabs
iter <- seq_len(terra::nlyr(x))[!terra::has.colors(x)]
if (length(iter) > 0 && min(iter) > 0) {
for (h in iter) {
# Assign coltab
tmpr <- terra::subset(x, h)
vals <- as.factor(pull(tmpr))
terra::values(tmpr) <- vals
df <- as_tibble(terra::cats(tmpr)[[1]])
coltb <- data.frame(
t(
col2rgb(terrain.colors(nrow(df), rev = TRUE),
alpha = TRUE
)
)
)
coltbend <- cbind(df[, 1], coltb)
terra::coltab(tmpr) <- coltbend
# Substitute layer
x[[h]] <- tmpr
}
}
lcats <- terra::cats(x)
# Get active cats by layer
actcats <- lapply(seq_len(terra::nlyr(x)), function(p) {
terra::activeCat(x[[p]])
})
# Prepare data frame with categories
lcats <- lapply(seq_len(terra::nlyr(x)), function(i) {
i_df <- lcats[[i]]
if (is.null(i_df)) {
return(NULL)
}
actcat <- unlist(actcats[i])
df <- i_df[, c(1, actcat + 1)]
names(df) <- c("id", "label")
df
})
# Add seq to names
nm <- paste0(names(x), "_", seq_len(terra::nlyr(x)))
names(lcats) <- nm
cats_end <- dplyr::bind_rows(lcats, .id = "layer")
# Get cols
cols_alpha_l <- terra::coltab(x)
cols_alpha_l <- lapply(cols_alpha_l, function(j) {
if (is.null(j)) {
return(NULL)
}
df <- j[, seq_len(5)]
names(df) <- c("id", "r", "g", "b", "a")
df
})
names(cols_alpha_l) <- nm
cols_end <- dplyr::bind_rows(cols_alpha_l, .id = "layer")
# Join and create
tojoin <- intersect(names(cats_end), names(cols_end))
finaltab <- dplyr::left_join(cats_end, cols_end, by = tojoin)
# Create palette
colfields <- finaltab[, c("r", "g", "b", "a")]
namedpal <- rgb(tidyr::drop_na(colfields), maxColorValue = 255)
# Same length than names
nms <- unique(finaltab[["label"]])
# Complete NAs with terrain.cols
if (!identical(length(namedpal), length(nms))) {
namedpal <- c(namedpal, terrain.colors(length(nms)))
namedpal <- namedpal[seq_len(length(nms))]
}
names(namedpal) <- nms
namedpal
}