-
Notifications
You must be signed in to change notification settings - Fork 641
Expand file tree
/
Copy pathkaleido.R
More file actions
232 lines (207 loc) · 8.11 KB
/
kaleido.R
File metadata and controls
232 lines (207 loc) · 8.11 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
231
232
#' Save plot as a static image
#'
#' Static image exporting via [the kaleido python
#' package](https://github.com/plotly/Kaleido/). `kaleido()` imports
#' kaleido into a \pkg{reticulate}d Python session and returns a `$transform()`
#' method for converting R plots into static images. `save_image()` provides a convenience wrapper around `kaleido()$transform()`.
#'
#' @section Installation:
#'
#' `kaleido()` requires [the kaleido python
#' package](https://github.com/plotly/Kaleido/) to be usable via the
#' \pkg{reticulate} package. If you're starting from scratch, you install
#' eveything you need with the following R code:
#'
#' ```
#' install.packages("reticulate")
#' library(reticulate)
#' use_python(install_python())
#' py_install(c("kaleido", "plotly"))
#' ```
#'
#' @param ... not currently used.
#' @param p a plot object.
#' @param file a file path with a suitable file extension (png, jpg, jpeg,
#' webp, svg, or pdf).
#' @param width,height The width/height of the exported image in layout
#' pixels. If `scale` is 1, this will also be the width/height of the exported
#' image in physical pixels.
#' @param scale The scale factor to use when exporting
#' the figure. A scale factor larger than 1.0 will increase the image
#' resolution with respect to the figure's layout pixel dimensions. Whereas as
#' scale factor of less than 1.0 will decrease the image resolution.
#' @export
#' @return For `save_image()`, the generated `file`. For `kaleido()`, an environment that contains:
#' * `transform()`: a function to convert plots objects into static images. This function has the same signature (i.e., arguments) as `save_image()`
#' * `shutdown()`: a function for shutting down any currently running subprocesses
#' that were launched via `transform()`
#' * `scope`: a reference to the underlying `kaleido.scopes.plotly.PlotlyScope`
#' python object. Modify this object to customize the underlying Chromium
#' subprocess and/or configure other details such as URL to plotly.js, MathJax, etc.
#' @examplesIf interactive() || !identical(.Platform$OS.type, "windows")
#'
#' \dontrun{
#' # Save a single image
#' p <- plot_ly(x = 1:10)
#' tmp <- tempfile(fileext = ".png")
#' save_image(p, tmp)
#' file.show(tmp)
#'
#' # Efficiently save multiple images
#' scope <- kaleido()
#' for (i in 1:5) {
#' scope$transform(p, tmp)
#' }
#' # Remove and garbage collect to remove
#' # R/Python objects and shutdown subprocesses
#' rm(scope); gc()
#' }
#'
save_image <- function(p, file, ..., width = NULL, height = NULL, scale = NULL) {
kaleido()$transform(
p, file, ..., width = width, height = height, scale = scale
)
}
#' @rdname save_image
#' @export
kaleido <- function(...) {
rlang::check_installed("reticulate")
call_env <- rlang::caller_env()
if (!reticulate::py_available(TRUE)) {
rlang::abort(c("`{reticulate}` wasn't able to find a Python environment.",
i = "If you have an existing Python installation, use `reticulate::use_python()` to inform `{reticulate}` of it.",
i = "To have `{reticulate}` install Python for you, `reticulate::install_python()`."
), call = call_env)
}
tryCatch(
reticulate::import("plotly"),
error = function(e) {
rlang::abort(c(
"The `plotly` Python package is required for static image exporting.",
i = "Please install it via `reticulate::py_install('plotly')`."
), call = call_env)
}
)
kaleido <- tryCatch(
reticulate::import("kaleido"),
error = function(e) {
rlang::abort(c(
"The `kaleido` Python package is required for static image exporting.",
i = "Please install it via `reticulate::py_install('kaleido')`."
), call = call_env)
}
)
res <- if (is.null(tryNULL(kaleido$scopes))) {
newKaleidoScope(kaleido)
} else {
legacyKaleidoScope(kaleido)
}
class(res) <- "kaleidoScope"
res
}
newKaleidoScope <- function(kaleido) {
list(
scopes = NULL,
transform = function(p, file, ..., width = NULL, height = NULL, scale = NULL) {
# Perform JSON conversion exactly how the R package would do it
fig_data <- plotly_build(p)$x[c("data", "layout", "config")]
# Inject mapbox token into layout.mapbox.accesstoken if available
# We use layout instead of config because Kaleido's parser preserves
# layout but drops config. This handles the case where users set
# MAPBOX_TOKEN env var but don't use plot_mapbox()
mapbox <- Sys.getenv("MAPBOX_TOKEN", NA)
if (!is.na(mapbox) && is.null(fig_data$layout$mapbox$accesstoken)) {
fig_data$layout$mapbox$accesstoken <- mapbox
}
fig <- to_JSON(fig_data)
# Write to JSON file
tmp_json <- tempfile(fileext = ".json")
on.exit(unlink(tmp_json))
writeLines(fig, tmp_json)
# Import it as a fig (dict)
load_json <- sprintf(
"import json; fig = json.load(open('%s'))",
tmp_json
)
reticulate::py_run_string(load_json)
# Gather figure-level options
opts <- list(
format = tools::file_ext(file),
width = reticulate::r_to_py(width),
height = reticulate::r_to_py(height),
scale = reticulate::r_to_py(scale)
)
# Pass the R plotly.js bundle path to Kaleido
kopts <- list(plotlyjs = plotlyMainBundlePath())
# Write the figure to a file using kaleido
kaleido$write_fig_sync(reticulate::py$fig, file, opts = opts, kopts = kopts)
},
shutdown = function() {}
)
}
legacyKaleidoScope <- function(kaleido) {
py <- reticulate::py
scope_name <- paste0("scope_", new_id())
py[[scope_name]] <- kaleido$scopes$plotly$PlotlyScope(
plotlyjs = plotlyMainBundlePath()
)
scope <- py[[scope_name]]
mapbox <- Sys.getenv("MAPBOX_TOKEN", NA)
if (!is.na(mapbox)) {
scope$mapbox_access_token <- mapbox
}
res <- list2env(list(
scope = scope,
# https://github.com/plotly/Kaleido/blob/6a46ecae/repos/kaleido/py/kaleido/scopes/plotly.py#L78-L106
transform = function(p, file = "figure.png", ..., width = NULL, height = NULL, scale = NULL) {
# Perform JSON conversion exactly how the R package would do it
# (this is essentially plotly_json(), without the additional unneeded info)
# and attach as an attribute on the python scope object
scope[["_last_plot"]] <- to_JSON(
plotly_build(p)$x[c("data", "layout", "config")]
)
# On the python side, _last_plot is a string, so use json.loads() to
# convert to dict(). This should be fine since json is a dependency of the
# BaseScope() https://github.com/plotly/Kaleido/blob/586be5/repos/kaleido/py/kaleido/scopes/base.py#L2
transform_cmd <- sprintf(
"%s.transform(sys.modules['json'].loads(%s._last_plot), format='%s', width=%s, height=%s, scale=%s)",
scope_name, scope_name, tools::file_ext(file),
reticulate::r_to_py(width), reticulate::r_to_py(height),
reticulate::r_to_py(scale)
)
# Write the base64 encoded string that transform() returns to disk
# https://github.com/plotly/Kaleido/blame/master/README.md#L52
reticulate::py_run_string(
sprintf("import sys; open('%s', 'wb').write(%s)", file, transform_cmd)
)
invisible(file)
},
# Shutdown the kaleido subprocesses
# https://github.com/plotly/Kaleido/blob/586be5c/repos/kaleido/py/kaleido/scopes/base.py#L71-L72
shutdown = function() {
reticulate::py_run_string(paste0(scope_name, ".__del__()"))
}
))
# Shutdown subprocesses and delete python scope when
# this object is garbage collected by R
reg.finalizer(res, onexit = TRUE, function(x) {
x$shutdown()
reticulate::py_run_string(paste("del", scope_name))
})
res
}
#' Print method for kaleido
#'
#' S3 method for [kaleido()].
#'
#' @param x a [kaleido()] object.
#' @param ... currently unused.
#' @export
#' @importFrom utils capture.output
#' @keywords internal
print.kaleidoScope <- function(x, ...) {
args <- formals(x$transform)
cat("$transform: function(", paste(names(args), collapse = ", "), ")\n", sep = "")
cat("$shutdown: function()\n")
cat("$scope: ", utils::capture.output(x$scope))
}