forked from easystats/modelbased
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinyplot.R
More file actions
230 lines (199 loc) · 6.57 KB
/
Copy pathtinyplot.R
File metadata and controls
230 lines (199 loc) · 6.57 KB
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
#' @rdname visualisation_recipe.estimate_predicted
#' @param type The type of `tinyplot` visualization. It is recommended that
#' users leave as `NULL` (the default), in which case the plot type will be
#' determined automatically by the underlying `modelbased` object.
#' @param dodge Dodge value for grouped plots. If `NULL` (the default), then
#' the dodging behavior is determined by the number of groups and
#' `getOption("modelbased_tinyplot_dodge")`.
#' @param ... Other arguments passed to \code{\link[tinyplot]{tinyplot}}.
#'
#' @examplesIf all(insight::check_if_installed(c("tinyplot", "marginaleffects"), quietly = TRUE))
#' # ==============================================
#' # tinyplot
#' # ==============================================
#' \donttest{
#' library(tinyplot)
#' data(efc, package = "modelbased")
#' efc <- datawizard::to_factor(efc, c("e16sex", "c172code", "e42dep"))
#' m <- lm(neg_c_7 ~ e16sex + c172code + barthtot, data = efc)
#'
#' em <- estimate_means(m, "c172code")
#' plt(em)
#'
#' # pass additional tinyplot arguments for customization, e.g.
#' plt(em, theme = "classic")
#' plt(em, theme = "classic", flip = TRUE)
#' # etc.
#'
#' # Aside: use tinyplot::tinytheme() to set a persistent theme
#' tinytheme("classic")
#'
#' # continuous variable example
#' em <- estimate_means(m, "barthtot")
#' plt(em)
#'
#' # grouped example
#' m <- lm(neg_c_7 ~ e16sex * c172code + e42dep, data = efc)
#' em <- estimate_means(m, c("e16sex", "c172code"))
#' plt(em)
#'
#' # use plt_add (alias tinyplot_add) to add layers
#' plt_add(type = "l", lty = 2)
#'
#' # Reset to default theme
#' tinytheme()
#' }
#' @exportS3Method tinyplot::tinyplot
tinyplot.estimate_means <- function(
x,
type = NULL,
dodge = NULL,
show_data = FALSE,
numeric_as_discrete = NULL,
...
) {
insight::check_if_installed("tinyplot")
# init --------------------------------------------------
response_scale <- attributes(x)$predict
model_info <- attributes(x)$model_info
# set defaults
if (is.null(numeric_as_discrete)) {
numeric_as_discrete <- getOption("modelbased_numeric_as_discrete", 8)
}
# we re-use the ggplot function here to retrieve the aesthetics and data. we
# now need to extract the aesthetics and data and use it to create a tinyplot
# object
aes <- .find_aes(x, model_info, numeric_as_discrete)
data <- aes$data
aes <- aes$aes
# save additional arguments, will pass via do.call to tinyplot
dots <- list(...)
# preparation of settings / arguments ----------------------------------
# Don't plot raw data if `predict` is not on the response scale
if (
!is.null(response_scale) &&
!response_scale %in% c("prediction", "response", "expectation", "invlink(link)")
) {
show_data <- FALSE
}
# Don't plot raw data for transformed responses with no back-transformation
transform <- attributes(x)$transform
if (isTRUE(model_info$is_linear) && !isTRUE(transform)) {
# add information about response transformation
trans_fun <- .safe(insight::find_transformation(attributes(x)$model))
if (!is.null(trans_fun) && all(trans_fun != "identity")) {
show_data <- FALSE
}
}
# type placeholder
if (!is.null(type)) {
aes$type <- type
}
# handle non-standard plot types -------------------------------
if (aes$type == "grouplevel") {
aes$type <- "pointrange"
dots$flip <- TRUE
}
# base elements as formula for tinyplot -------------------------------
# plot formula
if (is.null(aes$color)) {
plot_formula <- paste(aes$y, "~", aes$x)
} else {
plot_formula <- paste(aes$y, "~", aes$x, "|", aes$color)
}
plot_description <- stats::as.formula(plot_formula)
# facets, also as formula
if (is.null(dots$facet) && !is.null(aes$facet)) {
dots$facet <- stats::as.formula(paste("~", aes$facet, collapse = " + "))
}
# add remaining aesthetics to the plot description as symbols
elements <- c("xmin", "xmax", "ymin", "ymax")
plot_args <- lapply(elements, function(el) {
if (is.null(aes[[el]])) {
return(NULL)
}
as.symbol(aes[[el]])
})
names(plot_args) <- elements
# dodging -------------------------------
# Set dodge value for grouped point or pointrange plots.
# The value 0.07 was chosen to reduce overlap in this context; adjust via
# option if needed.
dodge_value <- if (!is.null(dodge)) {
dodge
} else {
getOption("modelbased_tinyplot_dodge", 0.07)
}
if (
!is.null(aes$color) &&
aes$type %in% c("pointrange", "point", "l", "errorbar", "ribbon")
) {
dots$dodge <- dodge_value
}
## TODO: show residuals?
# x/y labels --------------------------------
dots$xlab <- aes$labs$x
dots$ylab <- aes$labs$y
# legend labels --------------------------------
# we also need to account for custom legend options passed through dots
if (is.null(dots$legend)) {
dots$legend = list(title = aes$labs$colour)
} else if (inherits(dots$legend, "list")) {
if (!("title" %in% names(dots$legend))) {
dots$legend = utils::modifyList(
dots$legend,
list(title = aes$labs$colour),
keep.null = TRUE
)
}
} else if (!isFALSE(dots$legend)) {
dots$legend = tryCatch(
utils::modifyList(
as.list(dots$legend),
list(title = aes$labs$colour),
keep.null = TRUE
),
error = function(e) dots$legend
)
}
# add aesthetics to the plot description
plot_args <- insight::compact_list(c(
list(plot_description, data = data, type = aes$type),
plot_args,
dots
))
# add data points if requested --------------------------------
if (show_data) {
# extract raw data from the model
model <- attributes(x)$model
rawdata <- as.data.frame(insight::get_data(model, verbose = FALSE))
# set alpha
if (is.null(dots$alpha)) {
dots$alpha <- 0.3
}
# add layer
plot_args$draw <- {
tinyplot::tinyplot(
# we need the original response name for the data points
# so we update the formula for the plot description
stats::reformulate(
attr(stats::terms(plot_description), "term.labels"),
response = insight::find_response(model)
),
data = rawdata,
facet = dots$facet,
type = "jitter",
add = TRUE,
alpha = dots$alpha
)
}
}
# plot it!
suppressWarnings(do.call(tinyplot::tinyplot, plot_args))
}
#' @exportS3Method tinyplot::tinyplot
tinyplot.estimate_predicted <- tinyplot.estimate_means
#' @exportS3Method tinyplot::tinyplot
tinyplot.estimate_slopes <- tinyplot.estimate_means
#' @exportS3Method tinyplot::tinyplot
tinyplot.estimate_grouplevel <- tinyplot.estimate_means