Repository navigation
Expand file tree
/
Copy pathindex.Rmd
More file actions
313 lines (269 loc) · 11.3 KB
/
Copy pathindex.Rmd
File metadata and controls
313 lines (269 loc) · 11.3 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
---
title: "Week14 - Exporting Widgets"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
html_document:
theme: ~
toc: true
---
```{r echo=F}
### get knitr just the way we like it
knitr::opts_chunk$set(
message = FALSE
, warning = FALSE
, error = FALSE
, tidy = FALSE
, cache = FALSE
)
library(pipeR)
save_tags <- function (tags, file, selfcontained = F, libdir = "./lib", height="400px", width="100%")
{
if (is.null(libdir)) {
libdir <- paste(tools::file_path_sans_ext(basename(file)),
"_files", sep = "")
}
htmltools::save_html(tags, file = file, libdir = libdir)
if (selfcontained) {
if (!htmlwidgets:::pandoc_available()) {
stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n",
"https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
}
htmlwidgets:::pandoc_self_contained_html(file, file)
unlink(libdir, recursive = TRUE)
}
return(htmltools::tags$iframe(src= file, height = height, width = width, style="border:0;"))
}
```
## htmlwidgets News This Week
Just do this [Github search](https://github.com/search?o=desc&q=htmlwidgets&s=indexed&type=Code), and you'll likely see all the newest and latest. As a follow-up to last week's widget `stmBrowser`, I thought this research on [applications of `stm` to MOOCs](http://andrewgelman.com/2015/04/08/can-teachers-large-online-classes-use-text-data-online-learners/) is especially interesting.
## This Week's Widget - `exportwidget`
It seems exporting widgets is a popular request. This week's widget `exportwidget` offers an easy way to add an export to `PNG` button to other `htmlwidgets` or `SVG`. It works, but it is more an experiment and conversation starter for the broader discussion at [htmlwidgets issue #95](https://github.com/ramnathv/htmlwidgets/issues/95). There are lots of questions looking for answers.
- Why would you want to export an `htmlwidget`?
- How would you like to export an `htmlwidget` - clientside or headless?
- In what format would you like your exported `htmlwidget?
Thanks so much to the authors of [`canvg`](https://github.com/gabelerner/canvg), [`svg-crowbar`](https://github.com/NYTimes/svg-crowbar), and [`Download-File-JS`](https://github.com/PixelsCommander/Download-File-JS) on which `exportwidget` relies.
## Quick Installation
As with almost all widgets posted here, `exportwidget` is not on CRAN, so for now please install with `devtools::install_github`. Given enough interest, I'm happy to put in the effort to make this or any others CRAN-worthy. Just let me know.
```{r eval = F}
devtools::install_github("timelyportfolio/exportwidget")
```
## Examples
### Example With SVG + Custom Font
I'll start with what I think is the least likely use case of this widget but a demanding case that eliminates many of the `SVG` exporting JavaScript libraries. To conduct the test and as an extra benefit and proof of functionality, I'll add a custom font from Google Fonts with `htmlDependency` from `htmltools`. External fonts cause trouble in some of the other libraries I evaluated.
```{r "example01", echo=T, eval = F}
library(exportwidget)
library(htmltools)
library(pipeR)
tagList(
'<svg id = "svg_to_export" width="400" height="200">
<text x="50" y="100" text-anchor="start" dy="14" style="font-family:\'Indie Flower\';font-size:36pt;">
Custom Fonts
</text>
</svg>' %>>%
HTML
,export_widget( "svg" )
) %>>%
attachDependencies(list(
htmlDependency(
name = "IndieFlower"
,version = "0.1"
,src = c(href='http://fonts.googleapis.com/css?family=Indie+Flower')
,stylesheet = ""
)
))
```
```{r "example01_run", echo=F, eval = T}
library(exportwidget)
library(htmltools)
library(pipeR)
tagList(
'<svg id = "svg_to_export" width="400" height="200">
<text x="50" y="100" text-anchor="start" dy="14" style="font-family:\'Indie Flower\';font-size:36pt">
Custom Fonts
</text>
</svg>' %>>%
HTML
,export_widget( "svg" )
) %>>%
attachDependencies(list(
htmlDependency(
name = "IndieFlower"
,version = "0.1"
,src = c(href='http://fonts.googleapis.com/css?family=Indie+Flower')
,stylesheet = ""
)
)) %>>% save_tags("example01.html", height = "270px", width = "470px")
```
### Example with another widget `streamgraph`
[Alex Bresler](https://twitter.com/abresler/status/583050042099007489) assures me that streamgraphs are art, and thanks to [Bob Rudis \@hrbrmstr](http://rud.is/), there is an `htmlwidget` [`streamgraph`](http://rud.is/b/2015/03/12/streamgraph-htmlwidget-version-0-7-released-adds-support-for-markers-annotations/) for that. Let's see how we can use `exportwidget` to show somebody our "art". The `ChickWeight` dataset is definitely not the best for `streamgraphs` but it is small and built-in, so we'll go with it despite these issues.
```{r "example2", echo = T, eval = F}
library(dplyr)
library(streamgraph)
library(htmltools)
library(exportwidget)
# use the built in ChickWeight data set; not ideal but built-in
ChickWeight %>%
group_by( Diet, Time ) %>%
summarise( MeanWeight = mean(weight) ) %>%
streamgraph( "Diet", "MeanWeight", "Time", scale = "continuous" ) %>%
sg_legend( show = TRUE ) %>%
tagList(
export_widget( )
)
```
```{r "example2_run", echo = F, eval = T}
library(dplyr)
library(streamgraph)
library(htmltools)
# use the built in ChickWeight data set; not ideal but built-in
ChickWeight %>%
group_by( Diet, Time ) %>%
summarise( MeanWeight = mean(weight) ) %>%
streamgraph( "Diet", "MeanWeight", "Time", scale = "continuous", height = 400, width = 600 ) %>%
sg_legend( show = TRUE ) %>%
tagList(
export_widget( )
) %>>% save_tags("example02.html", height = "500px", width = "700px")
```
### Example with multiple widgets
Let's assume that we love our `htmlwidgets` and like to use lots of them on a page. `export_widget` without arguments will try to apply its button to all the `htmlwidgets` it finds. This could be bad. For instance, I doubt we would want to export a `navr`. If there are `htmlwidgets` in your page that you don't want to export, you'll probably want to be more specific in your `export_widget( )` and explicitly export just those `htmlwidgets`. As an example, with `grViz` from `DiagrammeR`, you could `export_widget(".grViz")` or with the `streamgraph` from the previous example, `export_widget(".streamgraph")`. Any `css` selector should work as an argument to `export_widget( )`.
Let's try it with [`DiagrammeR`](http://rich-iannone.github.io/DiagrammeR), [`rcdimple`](http://www.buildingwidgets.com/blog/2015/3/18/week-11-dimple-as-htmlwidget), and [`networkD3`](https://github.com/christophergandrud/networkD3).
```{r "example03", echo = T, eval = F}
library(htmltools)
library(DiagrammeR)
library(rcdimple)
library(networkD3)
library(exportwidget)
tagList(
# A slightly more involved example
# using example from http://www.graphviz.org/pdf/dotguide.pdf
# "Drawing graphs with dot"
# Emden R. Gansner and Eleftherios Koutsofios and Stephen North
# January 5, 2015
grViz('
digraph G {
size = "4,4";
main [shape = box]; /* this is a comment */
main -> parse [weight = 8];
parse -> execute;
main -> init [style = dotted];
main -> cleanup;
execute -> { make_string; printf}
init -> make_string;
edge [color = red]; // so is this
main -> printf;
node [shape = box, style = filled, color = ".7 .3 1.0"];
execute -> compare;
}
')
,dimple(
mtcars
, mpg ~ cyl
, groups = "cyl"
, type = "bubble"
) %>>%
default_colors( streamgraph:::tableau_colors( "tableau10medium" ) ) %>>%
set_bounds( x = "10%", y = "15%", width = "80%", height = "70%" )
,simpleNetwork(
data.frame(
Source = c("A", "A", "A", "A", "B", "B", "C", "C", "D")
,Target = c("B", "C", "D", "J", "E", "F", "G", "H", "I")
)
,height = 400
,width = 400
)
,export_widget()
)
```
```{r "example03_run", echo = F, eval = T}
library(htmltools)
library(DiagrammeR)
library(rcdimple)
library(networkD3)
library(exportwidget)
tagList(
# A slightly more involved example
# using example from http://www.graphviz.org/pdf/dotguide.pdf
# "Drawing graphs with dot"
# Emden R. Gansner and Eleftherios Koutsofios and Stephen North
# January 5, 2015
grViz('
digraph G {
size = "4,4";
main [shape = box]; /* this is a comment */
main -> parse [weight = 8];
parse -> execute;
main -> init [style = dotted];
main -> cleanup;
execute -> { make_string; printf}
init -> make_string;
edge [color = red]; // so is this
main -> printf;
node [shape = box, style = filled, color = ".7 .3 1.0"];
execute -> compare;
}
', height = 400, width = 400)
,dimple(
mtcars
, mpg ~ cyl
, groups = "cyl"
, type = "bubble"
, height = 400, width = 400
) %>>%
default_colors( streamgraph:::tableau_colors( "tableau10medium" ) ) %>>%
set_bounds( x = "10%", y = "15%", width = "80%", height = "70%" )
,simpleNetwork(
data.frame(
Source = c("A", "A", "A", "A", "B", "B", "C", "C", "D")
,Target = c("B", "C", "D", "J", "E", "F", "G", "H", "I")
)
,height = 400
,width = 400
)
,export_widget()
) %>>%
save_tags("example03.html", height = "900px", width = "600px")
```
### Example | Headless with `webshot`
Often, you might not want `exportwidget` at all. We very well might like a headless way to make a static copy of an `htmlwidget`. For this, we can use the excellent package [`webshot`](https://github.com/wch/webshot) by Winston Chang from RStudio. `webshot` uses the very widely used and tested `phantomjs`. We can push an `htmlwidget` through the pipe and get a `PNG` out the other end. Note, `webshot` and Windows aren't best friends yet. If you suffer through Windows like I do, then you can install my forked `webshot`.
```{r "example04", echo = T, eval = F}
library(networkD3)
library(webshot)
html_print(
simpleNetwork(
data.frame(
Source = c("A", "A", "A", "A", "B", "B", "C", "C", "D")
,Target = c("B", "C", "D", "J", "E", "F", "G", "H", "I")
)
,height = 400
,width = 400
)) %>>%
normalizePath(.,winslash="/") %>%
gsub(x=.,pattern = ":/",replacement="://") %>%
paste0("file:///",.) %>%
webshot( file = "headless_widget.png", delay = 2 )
```
```{r "example04_run", echo = F, eval = T}
library(webshot)
html_print(
simpleNetwork(
data.frame(
Source = c("A", "A", "A", "A", "B", "B", "C", "C", "D")
,Target = c("B", "C", "D", "J", "E", "F", "G", "H", "I")
)
,height = 400
,width = 400
)) %>>%
normalizePath(.,winslash="/") %>%
gsub(x=.,pattern = ":/",replacement="://") %>%
paste0("file:///",.) %>%
webshot( file = "headless_widget.png", delay = 2, selector = ".html-widget-static-bound" )
tags$img(src = base64enc::dataURI(file="./headless_widget.png",mime="image/png"))
```
## Thanks
Thanks so much for all the work by
- [`canvg`](https://github.com/gabelerner/canvg) from Gabe Lerner
- [`svg-crowbar`](https://github.com/NYTimes/svg-crowbar) from the NY Times
- [`Download-File-JS`](https://github.com/PixelsCommander/Download-File-JS) from Denis Radin
- Ramnath Vaidyanathan and RStudio for `htmlwidgets`
- all the contributors to `R`