-
Notifications
You must be signed in to change notification settings - Fork 1
/
seasyrplot.R
296 lines (239 loc) · 8.34 KB
/
seasyrplot.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#' Plot seasonal model response by years
#'
#' Plot seasonal model response by years on a common axis
#'
#' @param dat_in input tidal or tidalmean object
#' @param years numeric vector of years to plot
#' @param tau numeric vector of quantiles to plot, defaults to all in object if not supplied
#' @param predicted logical indicating if standard predicted values are plotted, default \code{TRUE}, otherwise normalized predictions are plotted
#' @param col_vec chr string of plot colors to use, passed to \code{\link{gradcols}}. Any color palette from RColorBrewer can be used as a named input. Palettes from grDevices must be supplied as the returned string of colors for each palette.
#' @param logspace logical indicating if plots are in log space
#' @param grids logical indicating if grid lines are present
#' @param pretty logical indicating if my subjective idea of plot aesthetics is applied, otherwise the \code{\link[ggplot2]{ggplot}} default themes are used
#' @param lwd numeric value indicating width of lines
#' @param alpha numeric value indicating transparency of points or lines
#' @param ... arguments passed to other methods
#'
#' @details The plot is similar to that produced by \code{\link{seasplot}} except the model estimates are plotted for each year as connected lines, as compared to loess lines fit to the model results. \code{\link{seasyrplot}} is also similar to \code{\link{sliceplot}} except the x-axis and legend grouping variable are flipped. This is useful for evaluating between-year differences in seasonal trends.
#'
#' Multiple predictions per month are averaged for a smoother plot.
#'
#' Note that the year variable used for color mapping is treated as a continuous variable although it is an integer by definition.
#'
#' @import dplyr ggplot2 RColorBrewer
#'
#' @export
#'
#' @return A \code{\link[ggplot2]{ggplot}} object that can be further modified
#'
#' @seealso \code{\link{seasplot}}, \code{\link{sliceplot}}
#'
#' @examples
#'
#' ## load a fitted tidal object
#' data(tidfit)
#'
#' # plot using defaults
#' seasyrplot(tidfit)
#'
#' # get the same plot but use default ggplot settings
#' seasyrplot(tidfit, pretty = FALSE)
#'
#' # plot specific quantiles
#' seasyrplot(tidfit, tau = c(0.9))
#'
#' # plot the normalized predictions
#' seasyrplot(tidfit, predicted = FALSE)
#'
#' # modify the plot as needed using ggplot scales, etc.
#'
#' library(ggplot2)
#'
#' seasyrplot(tidfit, pretty = FALSE, linetype = 'dashed') +
#' theme_classic() +
#' scale_y_continuous(
#' 'Chlorophyll',
#' limits = c(0, 5)
#' )
#'
#' # plot a tidalmean object
#' data(tidfitmean)
#'
#' seasyrplot(tidfitmean)
seasyrplot <- function(dat_in, ...) UseMethod('seasyrplot')
#' @rdname seasyrplot
#'
#' @export
#'
#' @method seasyrplot tidal
seasyrplot.tidal <- function(dat_in, years = NULL, tau = NULL, predicted = TRUE, logspace = TRUE, col_vec = NULL, grids = TRUE, pretty = TRUE, lwd = 0.5, alpha = 1, ...){
# sanity check
if(!any(grepl('^fit|^norm', names(dat_in))))
stop('No fitted data in tidal object, run modfit function')
# convert to df for plotting, get relevant columns
to_plo <- data.frame(dat_in)
sel_vec <- grepl('^year$|^month$|^fit|^norm', names(to_plo))
to_plo <- to_plo[, sel_vec]
# subset data by years
if(!is.null(years)){
to_plo <- filter(to_plo, year %in% years)
}
# get names of the quantiles for norms and preds to plot
if(is.null(tau)){
tau_fits <- grep('^fit', names(dat_in))
tau_fits <- floor(median(tau_fits))
tau_fits <- names(dat_in)[tau_fits]
tau_nrms <- gsub('^fit', 'norm', tau_fits)
} else {
if(length(tau) > 1)
stop('Only one quantile can be plotted')
if(length(grep(paste0(tau, '$'), names(dat_in))) == 0)
stop('Specified tau not in object')
tau_fits <- paste0('fit', tau)
tau_nrms <- paste0('norm', tau)
}
# create date vector with common year
names(to_plo)[names(to_plo) %in% tau_nrms] <- 'nrm'
names(to_plo)[names(to_plo) %in% tau_fits] <- 'fit'
to_plo <- select(to_plo, year, month, nrm, fit) %>%
group_by(year, month) %>%
summarize(
nrm = mean(nrm, na.rm = TRUE),
fit = mean(fit, na.rm = TRUE)
) %>%
ungroup %>%
mutate(
year_dum = '2000',
day = '01'
) %>%
tidyr::unite('date', year_dum, month, day, sep = '-') %>%
mutate(date = as.Date(date, '%Y-%m-%d')) %>%
na.omit
nrms <- select(to_plo, -fit)
fits <- select(to_plo, -nrm)
# y-axis label
ylabel <- attr(dat_in, 'reslab')
# back-transform if needed
if(!logspace){
nrms$nrm <- exp(nrms$nrm)
fits$fit <- exp(fits$fit)
# strip log, ln from yaxs label if there
ylabel <- gsub('ln-|log-', '', as.character(ylabel))
ylabel <- as.expression(parse(text = ylabel))
}
# plot fits or nrms
if(predicted){
p <- ggplot(fits, aes(x = date, y = fit, group = year, colour = year)) +
geom_line(alpha = alpha, lwd = lwd, na.rm = TRUE)
} else {
p <- ggplot(nrms, aes(x = date, y = nrm, group = year, colour = year)) +
geom_line(alpha = alpha, lwd = lwd, na.rm = TRUE)
}
# exit if pretty is F
if(!pretty) return(p)
##
# change aesthetics
# pick colors
cols <- gradcols(col_vec = col_vec)
# modify aesthetics
p <- p +
scale_colour_gradientn('Year', colours = cols) +
guides(colour = guide_colourbar(barwidth = 10)) +
theme_bw() +
theme(
legend.position = 'top',
axis.title.x = element_blank()
) +
scale_y_continuous(ylabel) +
scale_x_date(xlab, date_labels = "%m/%d")
# remove grid lines
if(!grids)
p <- p +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
return(p)
}
#' @rdname seasyrplot
#'
#' @export
#'
#' @method seasyrplot tidalmean
seasyrplot.tidalmean <- function(dat_in, years = NULL, tau = NULL, predicted = TRUE, logspace = TRUE, col_vec = NULL, grids = TRUE, pretty = TRUE, lwd = 0.5, alpha = 1, ...){
# sanity check
if(!any(grepl('^fit|^norm', names(dat_in))))
stop('No fitted data in tidal object, run modfit function')
# convert to df for plotting, get relevant columns
to_plo <- data.frame(dat_in)
sel_vec <- grepl('^year$|^month$|^fits$|^bt_fits$|^norm$|^bt_norm$', names(to_plo))
to_plo <- to_plo[, sel_vec]
# subset data by years
if(!is.null(years)){
to_plo <- filter(to_plo, year %in% years)
}
# create date vector with common year
to_plo <- group_by(to_plo, year, month) %>%
summarize(
fits = mean(fits, na.rm = TRUE),
bt_fits = mean(bt_fits, na.rm = TRUE),
norm = mean(norm, na.rm = TRUE),
bt_norm = mean(bt_norm, na.rm = TRUE)
) %>%
ungroup %>%
mutate(
year_dum = '2000',
day = '01'
) %>%
tidyr::unite('date', year_dum, month, day, sep = '-') %>%
mutate(date = as.Date(date, '%Y-%m-%d')) %>%
na.omit
nrms <- select(to_plo, -fits, -bt_fits)
fits <- select(to_plo, -norm, -bt_norm)
# y-axis label
ylabel <- attr(dat_in, 'reslab')
# back-transform if needed
if(!logspace){
nrms$nrm <- nrms$bt_norm
fits$fit <- fits$bt_fits
# strip log, ln from yaxs label if there
ylabel <- gsub('ln-|log-', '', as.character(ylabel))
ylabel <- as.expression(parse(text = ylabel))
} else {
nrms$nrm <- nrms$norm
fits$fit <- fits$fits
}
# plot fits or nrms
if(predicted){
p <- ggplot(fits, aes(x = date, y = fit, group = year, colour = year)) +
geom_line(alpha = alpha, lwd = lwd, na.rm = TRUE)
} else {
p <- ggplot(nrms, aes(x = date, y = nrm, group = year, colour = year)) +
geom_line(alpha = alpha, lwd = lwd, na.rm = TRUE)
}
# exit if pretty is F
if(!pretty) return(p)
##
# change aesthetics
# pick colors
cols <- gradcols(col_vec = col_vec)
# modify aesthetics
p <- p +
scale_colour_gradientn('Year', colours = cols) +
guides(colour = guide_colourbar(barwidth = 10)) +
theme_bw() +
theme(
legend.position = 'top',
axis.title.x = element_blank()
) +
scale_y_continuous(ylabel) +
scale_x_date(xlab, date_labels = "%m/%d")
# remove grid lines
if(!grids)
p <- p +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
return(p)
}