-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathtopics.Rmd
1093 lines (823 loc) · 59.2 KB
/
topics.Rmd
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (PART) Various special topics {-}
# Is plotly free and secure?
\sectionmark{Is plotly free and secure}
\indexc{api\_create()}
\index{config()@\texttt{config()}!cloud@\texttt{cloud}}
Yes! Both the R package and the underlying JavaScript library (plotly.js) are MIT licensed. That means you are free to distribute and commercialize anything you create with **plotly**. Optionally, you can sign up for a <https://plot.ly> account and use the `api_create()` function to upload **plotly** graphs to your account, but _a <https://plot.ly> account is not required to use **plotly**_.
Moreover, the data behind a **plotly** graph won't leave the computer you're viewing it on, unless:
* You sign up for a [plotly cloud](https://plot.ly/products/cloud/) account and use the `api_create()` function to upload your graph or data. This service is free for public-facing graphs, but private hosting costs money.
* You add the 'send data to cloud' modebar button. By default, this button is not included, but you can add it by doing `config(p, cloud = TRUE)`.
In other words, unless you specifically request otherwise, your graph runs entirely offline (i.e., no requests to external services are made). That means you can be confident that your data is not being shared with anyone/anything without your knowledge.
# Improving performance {#performance}
\sectionmark{Improving performance}
\index{toWebGL()@\texttt{toWebGL()}}
\indexc{partial\_bundle()}
Recall, from Figure \@ref(fig:intro-printing), when you print a **plotly** object (or really any plot), there are two classes of performance to be aware of: print-time (i.e., build) and runtime (i.e., render). That is, build time can be classified as the time it takes for the object to be serialized as JSON/HTML, whereas run time is the time it takes for the browser to render the HTML into a webpage. In the case of **plotly**, there are two quick and easy things you can do to improve run time performance in *any context*:
* `toWebGL()`: This function attempts to render the chart using WebGL (i.e., Canvas) instead of Scalable Vector Graphics (SVG). The difference between these contexts is somewhat analogous to the difference between saving a static chart to PNG/JPG (pixel based) versus PDF (vector based). Vector based graphics have the desirable property of producing sharp visuals that scale well to any size, but they don't scale well in the number of vectors (e.g., points, lines, polygons, etc.) that they need to render.
* `partial_bundle()`: This function attempts to reduce the size of the plotly.js bundle used to render the **plotly** graphs. The size of the default (i.e., main) plotly.js bundle is about 3MB, which can take a considerable amount of time to download with a slow internet connection, potentially leading to noticeable lag in initial page load for consumers of the graph. As it turns out, the main bundle is not always necessary to render every graph on a given website, so plotly.js provides [partial bundles](https://github.com/plotly/plotly.js/tree/master/dist#partial-bundles) that can render certain subsets of the graphing library. For instance, if you only need scatter, bar, or pie trace types, you can get away with the basic bundle which is currently under 1MB in size. This function is always safe to use when rendering a single **plotly** graph in a webpage, but when rendering multiple graphs, you should take care not to include multiple bundles in the same page.
These two options may improve runtime performance without much of any thinking, but sometimes it's worth being more thoughtful about your visualization strategy by leveraging summaries (e.g., Section \@ref(navigating-many-views), Figure \@ref(fig:shiny-crossfilter-kde), and Figure \@ref(fig:correlation-client-side)) as well as being more explicit about how a graph responds to changes in the underlying data (e.g., Section \@ref(proxies)). Mastering these more broad and complex subjects is critical for scaling interactive visualizations to truly large data^[Large data means different things to different people at different time periods. At the time of writing, I'd consider hundreds of millions of observations with at least a handful of variables to be large data.], especially in the case of linking multiple views, where computational 'tricks' such as pre-aggregating distributive (e.g., min, max, sum, count) and algebraic (e.g., mean, var, etc.) statistics intelligently is a trademark of systems that enable real-time graphical queries of massive datasets [@2013-immens; @nanocubes; @2019-falcon]. As @bigvis points out, it's also important to consider the uncertainty in these computationally efficient statistics, as they aren't nearly as statistically robust as their holistic counterparts (e.g., mean vs. median) that are more computationally intensive.
Since latency in interactive graphics is known to make exploratory data analysis a more challenging task [@2014-latency], systems that optimize run over build performance are typically preferable. This is especially true for visualizations that *others* are consuming, but in a typical EDA context, where the person creating the visualization is the main consumer, build time performance is also an important factor because it also presents a hurdle to the analytical thought process. It's hard to give general advice on improving build-time performance in general, but a great first step in doing so is to profile the speed of your R code with something like the **profvis** package. This will at least let you know if the slowness you're experiencing is due to your own R code.
# Controlling tooltips
\index{Tooltips@Tooltips (\texttt{text}, \texttt{hoverinfo}, \texttt{hoverformat}, \texttt{hovertemplate}, etc.)}
## `plot_ly()` tooltips {#tooltip-text}
There are two main approaches to controlling the tooltip: `hoverinfo` and `hovertemplate`. I suggest starting with the former approach since it's simpler, more mature, and enjoys universal support across trace types. On the other hand, `hovertemplate` does offer a convenient approach for flexible control over tooltip text, so it can be useful as well.
The `hoverinfo` attribute controls what other plot attributes are shown into the tooltip text. The default value of `hoverinfo` is `x+y+text+name` (you can verify this with `schema()`), meaning that plotly.js will use the relevant values of `x`, `y`, `text`, and `name` to populate the tooltip text. As Figure \@ref(fig:custom-tooltip-plotly) shows, you can supply custom text (without the other 'calculated values') by supplying a character string `text` and setting `hoverinfo = "text"`. The character string can include Glyphs, unicode characters, and some (white-listed) HTML entities and tags.^[If you find a tag or entity that you want that isn't supported, please request it to be added in the plotly.js repository <https://github.com/plotly/plotly.js/issues/new>] At least currently, plotly.js doesn't support rendering of [LaTeX](https://github.com/plotly/plotly.js/issues/559) or images in the tooltip, but as demonstrated in Figure \@ref(fig:tooltip-image), if you know some HTML/JavaScript, you can always build your own custom tooltip.
\index{layout()@\texttt{layout()}!barmode@\texttt{barmode}!stack}
\index{layout()@\texttt{layout()}!hovermode@\texttt{hovermode}}
```r
library(tibble)
library(forcats)
tooltip_data <- tibble(
x = " ",
y = 1,
categories = as_factor(c(
"Glyphs", "HTML tags", "Unicode",
"HTML entities", "A combination"
)),
text = c(
"👋 glyphs ಠ_ಠ",
"Hello <span style='color:red'><sup>1</sup>⁄<sub>2</sub></span>
fraction",
"\U0001f44b unicode \U00AE \U00B6 \U00BF",
"μ ± & < > × ± °",
paste("<b>Wow</b> <i>much</i> options", emo::ji("dog2"))
)
plot_ly(tooltip_data, hoverinfo = "text") %>%
add_bars(
x = ~x,
y = ~y,
color = ~fct_rev(categories),
text = ~text
) %>%
layout(
barmode ="stack",
hovermode = "x"
)
```
```{r custom-tooltip-plotly, echo = FALSE, fig.cap = "(ref:custom-tooltip-plotly)", dout.extra = if (knitr::is_html_output()) 'data-url="/interactives/custom-tooltip-plotly.html"'}
knitr::include_graphics("images/custom-tooltip-plotly.png")
```
Whenever a `fill` is relevant (e.g., `add_sf()`, `add_polygons()`, `add_ribbons()`, etc.), you have the option of using the `hoveron` attribute to generate a tooltip for the supplied data points, the filled polygon that those points define, or both. As Figure \@ref(fig:hoveron-fill-points) demonstrates, if you want a tooltip attached to a fill, you probably want `text` to be of length 1 for a given trace. On the other hand, if you want to each point along a fill to have a tooltip, you probably want `text` to have numerous strings.
\index{add\_trace()@\texttt{add\_trace()}!add\_polygons()@\texttt{add\_polygons()}!hoveron@\texttt{hoveron}}
```r
p <- plot_ly(
x = c(1, 2, 3),
y = c(1, 2, 1),
fill = "toself",
mode = "markers+lines",
hoverinfo = "text"
)
subplot(
add_trace(p, text = "triangle", hoveron = "fills"),
add_trace(p, text = paste0("point", 1:3), hoveron = "points")
)
```
```{r hoveron-fill-points, echo = FALSE, fig.cap = "(ref:hoveron-fill-points)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/hoveron-fill-points.html"'}
knitr::include_graphics("images/hoveron-fill-points.png")
```
\index{layout()@\texttt{layout()}!2D Axes!hoverformat@\texttt{hoverformat}}
You can't supply custom text in this way to a statistical aggregation, but there are ways to control the formatting of values computed and displayed by plotly.js (e.g., `x`, `y`, and `z`). If the value that you'd like to format corresponds to an axis, you can use `*axis.hoverformat`. The syntax behind `hoverformat` follows d3js' format conventions. For numbers, see: <https://github.com/d3/d3-format/blob/master/README.md#locale_format> and for dates see: <https://github.com/d3/d3-time-format/blob/master/README.md#locale_format>
```r
set.seed(1000)
plot_ly(x = rnorm(100), name = " ") %>%
add_boxplot(hoverinfo = "x") %>%
layout(xaxis = list(hoverformat = ".2f"))
```
```{r tooltip-format-boxplot, echo = FALSE, fig.cap = "(ref:tooltip-format-boxplot)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/tooltip-format-boxplot.html"'}
knitr::include_graphics("images/tooltip-format-boxplot.png")
```
Computed values that don't have a corresponding axis likely have a `*hoverformat` trace attribute. Probably the most common example is the `z` attribute in a `heatmap` or `histogram2d` chart. Figure \@ref(fig:tooltip-format-heatmap) shows how to format `z` values to have one decimal.
\index{layout()@\texttt{layout()}!2D Axes!hoverformat@\texttt{hoverformat}}
\index{add\_trace()@\texttt{add\_trace()}!add\_heatmap()@\texttt{add\_heatmap()}!zhoverformat@\texttt{zhoverformat}}
```r
plot_ly(z = ~volcano) %>%
add_heatmap(zhoverformat = ".1f") %>%
layout(xaxis = list(hoverformat = ".2f"))
```
```{r tooltip-format-heatmap, echo = FALSE, fig.cap = "(ref:tooltip-format-heatmap)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/tooltip-format-heatmap.html"'}
knitr::include_graphics("images/tooltip-format-heatmap.png")
```
It's admittedly difficult to remember where to specify these `hoverformat` attributes, so if you want a combination of custom text and formatting of computed values you can use `hovertemplate`, which overrides `hoverinfo` and allows you to fully specify the tooltip in a single attribute. It does this through special markup rules for inserting and formatting data values inside a string. Figure \@ref(fig:hovertemplate) provides an example of inserting `x` and `y` in the tooltip through the special `%{variable:format}` markup as well as customization of the secondary box through `<extra>` tag. For a full description of this attribute, including the formatting rules, see <https://plot.ly/r/reference/#scatter-hovertemplate>.
\index{add\_trace()@\texttt{add\_trace()}!add\_histogram()@\texttt{add\_histogram()}!histnorm@\texttt{histnorm}}
```r
set.seed(10)
plot_ly(x = rnorm(100, 0, 1e5)) %>%
add_histogram(
histnorm = "density",
hovertemplate = "The height between <br> (%{x}) <br> is %{y:.1e}
<extra>That's small!</extra>"
)
```
```{r hovertemplate, echo = FALSE, fig.cap = "(ref:hovertemplate)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/hovertemplate.html"'}
knitr::include_graphics("images/hovertemplate.png")
```
If you need really specific control over the tooltip, you might consider hiding the tooltip altogether (using `hoverinfo='none'`) and defining your own tooltip. Defining your own tooltip, however, will require knowledge of HTML and JavaScript; see Figure \@ref(fig:tooltip-image) for an example of how to display an image on hover instead of a tooltip.
## `ggplotly()` tooltips {#tooltip-text-ggplotly}
\index{ggplotly()@\texttt{ggplotly()}!Tooltip text}
Similar to how you can use the `text` attribute to supply a custom string in `plot_ly()` (see Section \@ref(tooltip-text)), you can supply a `text` aesthetic to your **ggplot2** graph, as shown in \@ref(fig:ggplotly-text):
```r
p <- ggplot(mtcars, aes(wt, mpg, text = row.names(mtcars))) +
geom_point()
ggplotly(p)
```
```{r ggplotly-text, echo = FALSE, fig.cap = "(ref:ggplotly-text)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/ggplotly-text.html"'}
knitr::include_graphics("images/ggplotly-text.png")
```
By default, `ggplotly()` will display all relevant aesthetic mappings (or computed values), but you can restrict what aesthetics are used to populate the tooltip, as shown in Figure \@ref(fig:ggplotly-text-tooltip):
```r
ggplotly(p, tooltip = "text")
```
```{r ggplotly-text-tooltip, echo = FALSE, fig.cap = "(ref:ggplotly-text-tooltip)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/ggplotly-text-tooltip.html"'}
knitr::include_graphics("images/ggplotly-text-tooltip.png")
```
When constructing the text to display, `ggplotly()` runs `format()` on the computed values. Since some parameters of the `format()` function can be controlled through global `options()`, you can use these `options()` to control the displayed text. This includes the `digits` option for controlling the number of significant digits used for numerical values as well as `scipen` for setting a penalty for deciding whether scientific or fixed notation is used for displaying. Figure \@ref(fig:format-options) shows how you can temporarily set these options (i.e., avoid altering of your global environment) using the **withr** package [@withr].
```r
library(withr)
p <- ggplot(faithfuld, aes(waiting, eruptions)) +
geom_raster(aes(fill = density))
subplot(
with_options(list(digits = 1), ggplotly(p)),
with_options(list(digits = 6, scipen = 20), ggplotly(p))
)
```
```{r format-options, echo = FALSE, fig.cap="(ref:format-options)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/format-options.html"'}
knitr::include_graphics("images/format-options.png")
```
These global options are nice for specifying significant/scientific notation, but what about more sophisticated formatting? Sometimes a clever use of the `text` aesthetic provides a sufficient workaround. Specifically, as Figure \@ref(fig:text-clever) shows, if one wanted to control a displayed aesthetic value (e.g., `y`), one could generate a custom string from that variable and supply it to `text`, then essentially replace `text` for `y` in the tooltip:
```r
library(scales)
p <- ggplot(txhousing, aes(date, median)) +
geom_line(aes(
group = city,
text = paste("median:", number_si(median))
))
ggplotly(p, tooltip = c("text", "x", "city"))
```
```{r text-clever, echo = FALSE, fig.cap="(ref:text-clever)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/text-clever.html"'}
knitr::include_graphics("images/text-clever.png")
```
The approach depicted in Figure \@ref(fig:text-clever) works for computed values that pertain to raw data values, but what about sophisticated formatting of a summary statistics generated by **ggplot2**? In this case, you'll have to use the return value of `ggplotly()` which, remember, is a **plotly** object that conforms to the plotly.js spec. That means you can identify trace attribute(s) that contain relevant info (**note:** the `plotly_json()` function is incredibly for helping to find that information), then use that info to populate a `text` attribute. Figure \@ref(fig:custom-predict-text) applies this technique to customize the text that appears when hovering over a `geom_smooth()` line.
\indexc{style()}
```r
# Add a smooth to the previous figure and convert to plotly
w <- ggplotly(p + geom_smooth(se = FALSE))
# This plotly object has two traces: one for
# the raw time series and one for the smooth.
# Try using `plotly_json(w)` to confirm the 2nd
# trace is the smooth line.
length(w$x$data)
# use the `y` attribute of the smooth line
# to generate a custom string (to appear in tooltip)
text_y <- number_si(
w$x$data[[2]]$y,
prefix = "Typical median house price: $"
)
# suppress the tooltip on the raw time series
# and supply custom text to the smooth line
w %>%
style(hoverinfo = "skip", traces = 1) %>%
style(text = text_y, traces = 2)
```
```{r custom-predict-text, echo = FALSE, fig.cap="(ref:custom-predict-text)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/custom-predict-text.html"'}
knitr::include_graphics("images/custom-predict-text.png")
```
## Styling
There is currently one main attribute for controlling the style of a tooltip: `hoverlabel`. With this attribute you can currently set the background color (`bgcolor`), border color (`bordercolor`), and font family/size/color. Figure \@ref(fig:tooltip-style) demonstrates how to use it with `plot_ly()` (basically any chart type you use should support it):
\index{Specifying fonts!hoverlabel@\texttt{hoverlabel}}
```r
font <- list(
family = "Roboto Condensed",
size = 15,
color = "white"
)
label <- list(
bgcolor = "#232F34",
bordercolor = "transparent",
font = font
)
plot_ly(x = iris$Petal.Length, hoverlabel = label)
```
```{r tooltip-style, echo = FALSE, fig.cap="(ref:tooltip-style)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/tooltip-style.html"'}
knitr::include_graphics("images/tooltip-style.png")
```
\indexc{style()}
\index{Specifying fonts!On-graph text}
On the other hand, when using `ggplotly()`, you have to modify the `hoverlabel` attribute via `style()` as shown in Figure \@ref(fig:tooltip-style-ggplotly)
```r
qplot(x = Petal.Length, data = iris) %>%
ggplotly() %>%
style(hoverlabel = label, marker.color = "#232F34") %>%
layout(font = font)
```
```{r tooltip-style-ggplotly, echo = FALSE, fig.cap="(ref:tooltip-style-ggplotly)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/tooltip-style-ggplotly.html"'}
knitr::include_graphics("images/tooltip-style-ggplotly.png")
```
As shown in Sections \@ref(tooltip-text) and \@ref(tooltip-text-ggplotly), the approach to customize the actual text of a tooltip is slightly different depending on whether you're using `ggplotly()` or `plot_ly()`, but styling the appearance of the tooltip is more or less the same in either approach.
# Control the modebar {#control-modebar}
By default, the modebar appears in the top right-hand side of a **plotly** graph on mouse hover, and can lead to poor user-experience on small displays. Fortunately, the modebar can be completely customized via the `config()` function. The `config()` function can be helpful for a lot of things: language support (Chapter \@ref(locales)), enabling mathjax (Chapter \@ref(mathjax)), suppressing tip notifications (e.g., `showTips`), when to scroll on zoom, etc. However, this topic is all about options related to the modebar. To see a complete list of `config()` options, as well as their description, see the config section of the plotly.js `schema()`.
## Remove the entire modebar
The `displayModeBar` option makes it quick and easy to remove the entire modebar.
\index{config()@\texttt{config()}!displayModeBar@\texttt{displayModeBar}}
```r
plot_ly() %>%
config(displayModeBar = FALSE)
```
## Remove the plotly logo
The `displaylogo` option makes it quick and easy to remove the entire modebar.
\index{config()@\texttt{config()}!displaylogo@\texttt{displaylogo}}
```r
plot_ly() %>%
config(displaylogo = FALSE)
```
```{r displaylogo, echo = FALSE, fig.cap = "(ref:displaylogo)"}
knitr::include_graphics("images/displaylogo.png")
```
## Remove modebar buttons by name
\index{config()@\texttt{config()}!modeBarButtonsToRemove@\texttt{modeBarButtonsToRemove}}
Any modebar buttons can be removed by name via `modeBarButtonsToRemove`. Figure \@ref(fig:modeBarButtonsToRemove) demonstrates removal of the 2D zoom in and out button. The full list of modebar buttons included by default can be found at <https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js>
```r
plot_ly() %>%
config(modeBarButtonsToRemove = c("zoomIn2d", "zoomOut2d"))
```
```{r modeBarButtonsToRemove, echo = FALSE, fig.cap = "(ref:modeBarButtonsToRemove)"}
knitr::include_graphics("images/modeBarButtonsToRemove.png")
```
## Add custom modebar buttons
It is possible to supply your own modebar button icon that triggers a custom JavaScript function when clicked. You must provide a `name` for the icon and either a SVG `path` (with just the d attribute) or a full SVG element (to `svg`). Nowadays, there are a number of free websites that allow you to search icons and download their corresponding SVG information. When supplying `path`, as in Figure \@ref(fig:modeBarButtonsToAdd), you can also define an SVG `transform` to help size and position the icon. To define a JavaScript function to call upon clicking the icon, you can provide a string to `htmlwidgets::JS()`. The interactive version of Figure \@ref(fig:modeBarButtonsToAdd) adds on-graph text every time the octocat icon is clicked. To learn more about how to leverage JavaScript from R, see Chapter \@ref(javascript).
\index{config()@\texttt{config()}!modeBarButtonsToAdd@\texttt{modeBarButtonsToAdd}}
```r
data(octocat_svg_path, package = "plotlyBook")
octocat <- list(
name = "octocat",
icon = list(
path = octocat_svg_path,
transform = 'matrix(1 0 0 1 -2 -2) scale(0.7)'
),
click = htmlwidgets::JS(
"function(gd) {
var txt = {x: [1], y: [1], text: 'Octocat!', mode: 'text'};
Plotly.addTraces(gd, txt);
}"
)
)
plot_ly() %>%
config(modeBarButtonsToAdd = list(octocat))
```
```{r modeBarButtonsToAdd, echo = FALSE, fig.cap = "(ref:modeBarButtonsToAdd)"}
knitr::include_graphics("images/modeBarButtonsToAdd.png")
```
Note that you can also use `modeBarButtons` to completely specify which buttons to include in the modebar. As shown in Figure \@ref(fig:modeBarButtons), with this option, you can supply existing button names and/or your own custom buttons:
\index{config()@\texttt{config()}!modeBarButtons@\texttt{modeBarButtons}}
```r
plot_ly() %>%
config(modeBarButtons = list(list("zoomIn2d"), list(octocat)))
```
```{r modeBarButtons, echo = FALSE, fig.cap = "(ref:modeBarButtons)"}
knitr::include_graphics("images/modeBarButtons.png")
```
## Control image downloads
\index{config()@\texttt{config()}!toImageButtonOptions@\texttt{toImageButtonOptions}}
By default, the `toImage` modebar button downloads a PNG file using the current size and state of the graph. With `toImageButtonOptions`, one can specify different sizes and filetypes, which is particularly useful for obtaining a static PDF/WebP/JPG/etc. image of the plot *after* components have been directly manipulated, as leveraged in Figure \@ref(fig:edit-county-labels). Here's a basic example of configuring the `'toImage'` button to download an SVG file that's 200 x 100 pixels:
```r
plot_ly() %>%
config(
toImageButtonOptions = list(
format = "svg",
width = 200,
height = 100
)
)
```
After downloading the SVG file, you can convert it to PDF using the `rsvg_pdf()` function from the **rsvg** package [@rsvg].
# Working with colors {#working-with-colors}
\sectionmark{Working with colors}
The JavaScript library underlying **plotly** (plotly.js) has its own support for specifying colors, which is different from how R specifies colors. It currently supports:
* hex (e.g., `"#FF0000"`)
* rgb (e.g., `"rgb(255, 0, 0)"`)
* rgba (e.g., `"rgba(255, 0, 0, 1)"`)
* hsl (e.g., `'hsl(0, 100%, 50%)'`)
* hsv (e.g., `'hsv(0, 100%, 50%)'`)
* Named CSS3 colors <http://www.w3.org/TR/css3-color/#svg-color>
If you use `plot_ly()` and directly specify a plotly.js color attribute (e.g., `marker.color`), you can use any of these formats. Figure \@ref(fig:color-plotly-js) uses the hsl format:
```r
plot_ly(
x = iris$Petal.Length,
marker = list(color = "hsl(0, 100%, 50%)")
)
```
```{r color-plotly-js, echo = FALSE, fig.cap="(ref:color-plotly-js)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/color-plotly-js.html"'}
knitr::include_graphics("images/color-plotly-js.png")
```
If you're doing something specific to R, like using `ggplotly()` and/or the top-level `color`/`colors`/`stroke`/`strokes` argument in `plot_ly()`, you'll need to be careful about specifying colors in a way that R and **plotly** can understand. For example, at least currently, you can't specify an hsl string in this way:
```r
plot_ly(x = 1, y = 1, color = I("hsl(0, 100%, 50%)"))
```
```r
#> Error in grDevices::col2rgb(x, alpha = TRUE):
#> invalid color name 'hsl(0, 100%, 50%)'
```
Just like in **ggplot2**, you'll have to specify a color in one of the following ways:
* A hexadecimal string of the form "#rrggbb" or "#rrggbbaa".
* Named colors (e.g., "blue"). All supported names are listed in `colors()`.
* An `NA` for transparent.
This doesn't imply that you can't work in other colorspaces though (e.g., rgb, rgba, hsl, or hsl). The **colorspace** package provides a nice way to create colors in any of these colorspaces and provides a `hex()` function that you can use to convert any color to a hexadecimal format [@colorspace].
```r
library(colorspace)
red <- hex(HLS(0, 0.5, 1))
plot_ly(x = iris$Petal.Length, color = I(red))
```
If you'd like to see more examples of specifying colors, see Chapter \@ref(scatter-traces).
# Working with symbols and glyphs {#working-with-symbols}
\sectionmark{Working with symbols and glyphs}
The JavaScript library underlying **plotly** (plotly.js) has its own special support for specifying marker symbols by name. As Figure \@ref(fig:symbols-all) shows, there are currently many acceptable `marker.symbol` values, and all the acceptable values can be accessed through plotly.js's `schema()`.
```{r, eval = FALSE, code = readLines("code/symbols-all.R")}
```
```{r symbols-all, echo = FALSE, fig.cap = "(ref:symbols-all)", code = readLines("code/symbols-all-output.R")}
```
In addition to these marker symbols, you can also use `add_text()` to encode data with on-graph text. Moreover, the `add_text()` function (i.e., a scatter trace with `mode="markers"`) enjoys a lot of the same properties as `add_markers()` (i.e., a scatter trace with `mode="text"`). As Figure \@ref(fig:glyphs) shows, similar to how we can supply typographical glyphs and/or unicode in a custom tooltip, you can supply a character vector of similar content to `add_text()` (i.e., a scatter trace with `mode='text'`) which renders on-graph text. Furthermore, when using `text` to render on-graph text, one can leverage the `hovertext` attribute to display some different text on hover.
```r
plot_ly() %>%
add_text(
x = rep(2, 2),
y = 1:2,
size = I(15),
text = c(
"Glyphs: Ѳ, (╯°□°)╯ ┻━┻",
"Unicode: \U00AE \U00B6 \U00BF"
),
hovertext = c(
"glyphs",
"unicode"
),
textposition = "left center",
hoverinfo = "text"
)
```
```{r glyphs, echo = FALSE, fig.cap = "(ref:glyphs)", , out.extra = if (knitr::is_html_output()) 'data-url="/interactives/glyphs.html"'}
knitr::include_graphics("images/glyphs.svg")
```
Having the ability to encode data with unicode means that we have a virtually endless number of ways to encode data in symbols/glyphs. Just for fun, Figure \@ref(fig:emojis) demonstrates how you could plot all the activity emojis using the **emo** package and display the name of the emoji on hover [@emo].
```r
library(emo)
set.seed(100)
jis %>%
filter(group == "Activities") %>%
plot_ly(x = runif(nrow(.)), y = runif(nrow(.))) %>%
add_text(
text = ~emoji,
hovertext = ~name,
hoverinfo = "text",
size = I(20)
)
```
```{r emojis, echo = FALSE, fig.cap = "(ref:emojis)"}
knitr::include_graphics("images/emojis.png")
```
<!--
# Control the layout
## Axis titles
## Axis labels
* using factors to control ordering of axis labels
* specifying your own tickvals/ticktext?
* discuss pros and cons
## Margins
## Fonts
-->
# Embedding images
\sectionmark{Embedding images}
\index{layout()@\texttt{layout()}!images@\texttt{images}!URL}
There are a few ways to embed images in a **plotly** graph. Perhaps the easiest is to point the image source to a hyperlink containing a bitmap file (e.g., PNG, JPG, etc.).
\index{layout()@\texttt{layout()}!margin@\texttt{margin}}
```r
plot_ly() %>%
layout(
images = list(
source = "https://www.rstudio.com/wp-content/uploads/2018/10/
RStudio-Logo-Flat.png",
x = 0, y = 1,
sizex = 0.2, sizey = 0.1,
xref = "paper", yref = "paper",
xanchor = "left", yanchor = "bottom"
),
margin = list(t = 50)
)
```
```{r image-hyperlink, echo = FALSE, fig.cap="(ref:image-hyperlink)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/image-hyperlink.html"'}
knitr::include_graphics("images/image-hyperlink.svg")
```
The approach in Figure \@ref(fig:image-hyperlink) has a downside though: if that hyperlink breaks, then so does your plot. It'd be better to download the file to your machine and use the `dataURI()` function from the **base64enc** package (or similar) to embed the image as a data URI as done in Figure \@ref(fig:image-uri) [@base64enc]:
\index{layout()@\texttt{layout()}!images@\texttt{images}!base64 encoded}
```r
plot_ly() %>%
layout(
images = list(
source = base64enc::dataURI(file = "images/rstudio.png"),
x = 0, y = 1,
sizex = 0.2, sizey = 0.1,
xref = "paper", yref = "paper",
xanchor = "left", yanchor = "bottom"
),
margin = list(t = 50)
)
```
```{r image-uri, echo = FALSE, fig.cap="(ref:image-uri)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/image-uri.html"'}
knitr::include_graphics("images/image-uri.svg")
```
Another approach is to convert a raster object into a data URI, which the `raster2uri()` function in **plotly** is designed to do. R actually ships with native support for raster objects and many image processing R packages either build on this data structure or provide a utility to convert to a raster object (perhaps via `as.raster()`). As done in Figure \@ref(fig:raster), the `readPNG()` function from the **png** package reads image data in an R array, which can be converted to a raster object [@png].
\index{layout()@\texttt{layout()}!images@\texttt{images}!raster2uri()@\texttt{raster2uri()}}
```r
pen <- png::readPNG("images/penguin.png")
plot_ly() %>%
layout(
images = list(
source = raster2uri(as.raster(pen)),
x = 2, y = 2,
sizex = 2, sizey = 1,
xref = "x", yref = "y",
xanchor = "left", yanchor = "bottom",
sizing = "stretch"
)
)
```
```{r raster, echo = FALSE, fig.cap = "(ref:raster)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/raster.html"'}
knitr::include_graphics("images/raster.svg")
```
Moreover, thanks to the R package **magick**, it's possible to rasterize non-raster file formats (e.g., PDF, SVG, etc.) directly in R, so if you wanted, you could also embed non-bitmap images by using `image_read()` and `image_convert()` to generate a raster object [@magick].
# Language support {#locales}
\sectionmark{Language support}
\index{config()@\texttt{config()}!locale@\texttt{locale}}
The `locale` argument of the `config()` function allows one to render on-graph text using another language. Figure \@ref(fig:localization) shows how setting `locale='ja'` will render text in Japanese.
```r
today <- Sys.Date()
x <- seq.Date(today, today + 360, by = "day")
plot_ly(x = x, y = rnorm(length(x))) %>%
add_lines() %>%
config(locale = "ja")
```
```{r localization, echo = FALSE, fig.cap="(ref:localization)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/localization.html"'}
knitr::include_graphics("images/localization.png")
```
Table \@ref(tab:locale-codes) contains a list of all the supported locale codes and the language they correspond to.
```{r, echo = FALSE}
locales <- list.files(system.file("htmlwidgets/lib/plotlyjs/locales", package = "plotly"))
locale_codes <- tibble::tibble(
Code = tools::file_path_sans_ext(locales)
)
data(locale_table, package = "plotlyBook")
locale_df <- locale_table %>%
dplyr::select(Language = Locale, Code = Languagecode) %>%
dplyr::semi_join(locale_codes)
if (knitr::is_html_output())
DT::datatable(locale_df, rownames = FALSE)
```
```{r locale-codes, echo = FALSE, results='asis'}
if (knitr::is_html_output()) {
cat("<table>", paste0("<caption>", "(#tab:locale-codes)", "Language support in plotly. To use one of these languages, supply the locale code to the <code>locale</code> argument in the <code>config()</code> function.", "</caption>"),"</table>", sep ="\n")
} else {
knitr::kable(locale_df, "latex", booktabs = TRUE, longtable = TRUE, caption = "Language support in plotly. To use one of these languages, supply the locale code to the \\texttt{locale} argument in the \\texttt{config()} function.") %>%
kableExtra::kable_styling(latex_options = c("hold_position", "repeat_header"))
}
```
# LaTeX rendering {#mathjax}
\sectionmark{LaTeX rendering}
\index{config()@\texttt{config()}!mathjax@\texttt{mathjax}}
\index{layout()@\texttt{layout()}!title@\texttt{title}}
\index{layout()@\texttt{layout()}!2D Axes!title@\texttt{title}}
LaTeX rendering via MathJax is possible via the `TeX()` function which flags a character vector as LaTeX. To load MathJaX externally (meaning an internet connection is needed for TeX rendering), set the new `mathjax` argument in `config()` to `"cdn"`. Figure \@ref(fig:mathjax) demonstrates how to render LaTeX in the plot and axis titles.
```r
library(plotly)
data(co2, package = "datasets")
plot_ly() %>%
add_lines(x = zoo::index(co2), y = co2) %>%
layout(
title = TeX("CO_2 \\text{measured in } \\frac{parts}{million}"),
xaxis = list(title = "Time"),
yaxis = list(
title = TeX("\\text{Atmospheric concentration of CO}_2")
)
) %>%
config(mathjax = "cdn")
```
```{r mathjax, echo = FALSE, fig.cap="(ref:mathjax)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/mathjax.html"'}
knitr::include_graphics("images/mathjax.svg")
```
Figure \@ref(fig:mathjax2) demonstrates how to render LaTeX with on-graph text. There are two ways to draw on-graph text: `add_text()` which is a scatter trace with a mode of text and `add_annotations()` which is part of the graph's layout. The main difference is that `add_text()` is able to display tooltips and `add_annotations()` is able to display arrows.
\index{add\_annotations()@\texttt{add\_annotations()}!TeX()@\texttt{TeX()}}
\index{add\_trace()@\texttt{add\_trace()}!add\_text()@\texttt{add\_text()}}
```r
plotly_empty(showlegend = FALSE, hoverinfo = "x+y") %>%
add_annotations(
x = 1, y = 2,
showarrow = FALSE,
text = TeX(
"\\text{The sample mean:} \\sum_{i=1}^n x_i \\text{ where}"
)
) %>%
add_text(
x = 1, y = 1, size = I(100),
text = TeX("x_i \\sim N(\\mu, \\sigma)")
) %>%
add_annotations(x = 1, y = 0, text = TeX("E[x_i]")) %>%
add_text(
x = 1, y = 0, text = TeX("\\mu"), textposition = "bottom"
) %>%
config(mathjax = "cdn")
```
```{r mathjax2, echo = FALSE, fig.cap="(ref:mathjax2)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/mathjax2.html"'}
knitr::include_graphics("images/mathjax2.png")
```
To use a local version of MathJax (so that your graphs will render without an internet connection), you need to inform **plotly** where it's located. If you don't already have MathJax locally, I recommend downloading the official MathJax git repo. Here's how to do that using terminal commands:
```shell
$ git clone https://github.com/mathjax/MathJax.git
$ cd MathJax
```
Now set the `PLOTLY_MATHJAX_PATH` environment variable so that **plotly** knows where that MathJax folder lives. I recommend setting this variable in you `.Rprofile` so you don't have to reset it every time you restart R:
```shell
$ export PLOTLY_MATHJAX_PATH=`pwd`
$ echo "Sys.setenv('PLOTLY_MATHJAX_PATH' = '$PLOTLY_MATHJAX_PATH')" >>
+ ~/.Rprofile
```
Finally, once `PLOTLY_MATHJAX_PATH` is set, specify `mathjax="local"` in `config()`:
```r
config(last_plot(), mathjax = "local")
```
## MathJax caveats
1. MathJax rendering in tooltips [currently isn't supported](https://github.com/plotly/plotly.js/issues/559).
2. At least currently, plotly.js requires SVG-based rendering which doesn't play nicely with HTML-based rendering (e.g., **rmarkdown** documents and **shiny** apps) . If you need both the SVG and HTML rendering, consider `<iframe>`-ing your plotly graph(s) into the larger document (see [here](https://github.com/ropensci/plotly/blob/master/inst/examples/rmd/MathJax/index.Rmd) for an example).
3. Due to the size and nature of MathJax, using `htmlwidget::saveWidget()` with `selfcontained = TRUE` won't work. At least for now, when you need to save a plotly graph (`p`) with local MathJax, do `htmlwidget::saveWidget(p, selfcontained = FALSE)`
# The data-plot-pipeline
\sectionmark{The data-plot-pipeline}
\index{Data-plot-pipeline}
As Section \@ref(intro-plotly) first introduced, we can express multi-layer **plotly** graphs as a sequence (or, more specifically, a directed acyclic graph) of **dplyr** data manipulations and mappings to visuals. For example, to create Figure \@ref(fig:houston2), we could group `txhousing` by `city` to ensure the first layer of `add_lines()` draws a different line for each city, then `filter()` down to Houston so that the second call to `add_lines()` draws only Houston.
```r
allCities <- txhousing %>%
group_by(city) %>%
plot_ly(x = ~date, y = ~median) %>%
add_lines(alpha = 0.2, name = "Texan Cities", hoverinfo = "none")
allCities %>%
filter(city == "Houston") %>%
add_lines(name = "Houston")
```
```{r houston2, echo = FALSE, fig.cap = "(ref:houston2)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/houston2.html"'}
knitr::include_graphics("images/houston2.svg")
```
Sometimes, the directed acyclic graph property of a **magrittr** pipeline can be too restrictive for certain types of plots. In this example, after filtering the data down to Houston, there is no way to recover the original data inside the pipeline. The `add_fun()` function helps to workaround this restriction^[Credit to Winston Chang and Hadley Wickham for this idea. The `add_fun()` is very much like `layer_f()` function in **ggvis**.]; it works by applying a function to the plotly object, but does not affect the data associated with the plotly object. This effectively provides a way to isolate data transformations within the pipeline^[Effectively putting a pipeline inside a pipeline]. Figure \@ref(fig:houston-vs-sa) uses this idea to highlight both Houston and San Antonio.
\index{Data-plot-pipeline!add\_fun()@\texttt{add\_fun()}}
```r
allCities %>%
add_fun(function(plot) {
plot %>% filter(city == "Houston") %>%
add_lines(name = "Houston")
}) %>%
add_fun(function(plot) {
plot %>% filter(city == "San Antonio") %>%
add_lines(name = "San Antonio")
})
```
```{r houston-vs-sa, echo = FALSE, fig.cap = "(ref:houston-vs-sa)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/houston-vs-sa.html"'}
knitr::include_graphics("images/houston-vs-sa.svg")
```
It is useful to think of the function supplied to `add_fun()` as a "layer" function; a function that accepts a plot object as input, possibly applies a transformation to the data, and maps that data to visual objects. To make layering functions more modular, flexible, and expressive, the `add_fun()` allows you to pass additional arguments to a layer function. Figure \@ref(fig:summary) makes use of this pattern, by creating a reusable function for layering both a particular city as well as the first, second, and third quartile of median monthly house sales (by city).
```r
# reusable function for highlighting a particular city
layer_city <- function(plot, name) {
plot %>% filter(city == name) %>% add_lines(name = name)
}
# reusable function for plotting overall median & IQR
layer_iqr <- function(plot) {
plot %>%
group_by(date) %>%
summarise(
q1 = quantile(median, 0.25, na.rm = TRUE),
m = median(median, na.rm = TRUE),
q3 = quantile(median, 0.75, na.rm = TRUE)
) %>%
add_lines(y = ~m, name = "median", color = I("black")) %>%
add_ribbons(
ymin = ~q1, ymax = ~q3,
name = "IQR", color = I("black")
)
}
allCities %>%
add_fun(layer_iqr) %>%
add_fun(layer_city, "Houston") %>%
add_fun(layer_city, "San Antonio")
```
```{r summary, echo = FALSE, fig.cap = "(ref:summary)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/summary.html"'}
knitr::include_graphics("images/summary.svg")
```
A layering function does not have to be a data-plot-pipeline itself. Its only requirement on a layering function is that the first argument is a plot object and it returns a plot object. This provides an opportunity to say, fit a model to the plot data, extract the model components you desire, and map those components to visuals. Furthermore, since **plotly**'s `add_*()` functions don't require a data.frame, you can supply those components directly to attributes (as long as they are well defined), as done in Figure \@ref(fig:forecast) via the **forecast** package [@forecast].
\indexc{plotly\_data()}
\indexc{forecast()}
\index{add\_trace()@\texttt{add\_trace()}!add\_ribbons()@\texttt{add\_ribbons()}}
```r
library(forecast)
layer_forecast <- function(plot) {
d <- plotly_data(plot)
series <- with(d,
ts(median, frequency = 12, start = c(2000, 1), end = c(2015, 7))
)
fore <- forecast(ets(series), h = 48, level = c(80, 95))
plot %>%
add_ribbons(x = time(fore$mean), ymin = fore$lower[, 2],
ymax = fore$upper[, 2], color = I("gray95"),
name = "95% confidence", inherit = FALSE) %>%
add_ribbons(x = time(fore$mean), ymin = fore$lower[, 1],
ymax = fore$upper[, 1], color = I("gray80"),
name = "80% confidence", inherit = FALSE) %>%
add_lines(x = time(fore$mean), y = fore$mean, color = I("blue"),
name = "prediction")
}
txhousing %>%
group_by(city) %>%
plot_ly(x = ~date, y = ~median) %>%
add_lines(alpha = 0.2, name = "Texan Cities", hoverinfo="none") %>%
add_fun(layer_iqr) %>%
add_fun(layer_forecast)
```
```{r forecast, echo = FALSE, fig.cap = "(ref:forecast)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/forecast.html"'}
knitr::include_graphics("images/forecast.svg")
```
In summary, the "data-plot-pipeline" is desirable for a number of reasons: (1) makes your code easier to read and understand, (2) encourages you to think of both your data and plots using a single, uniform data structure, which (3) makes it easy to combine and reuse transformations.
# Improving `ggplotly()` {#improving-ggplotly}
\sectionmark{Improving ggplotly}
\index{ggplotly()@\texttt{ggplotly()}!Modification}
Since the `ggplotly()` function returns a **plotly** object, we can use that object in the same way you can use any other **plotly** object. Modifying this object is _always_ going to be useful when you want more control over certain (interactive) behavior that **ggplot2** doesn't provide an API to describe^[It can also be helpful for correcting translations that `ggplotly()` doesn't get quite right.], for example:
\indexc{style()}
* `layout()` for modifying aspects of the layout, which can be used to do many things, for example:
* Change default [`hovermode`](https://plot.ly/r/reference/#layout-hovermode) behavior (See Figure \@ref(fig:ggplotly-rangeslider)).
* Stylizing hover labels ([`hoverlabel`](https://plot.ly/r/reference/#layout-hoverlabel)).
* Changing click+drag mode ([`dragmode`](https://plot.ly/r/reference/#layout-dragmode)) and/or constraining rectangular selections (`dragmode='select'`) vertically or horizontally ([`selectdirection`](https://plot.ly/r/reference/#layout-selectdirection)).
* Add dropdowns <https://plot.ly/r/dropdowns/>, sliders <https://plot.ly/r/sliders/>, and rangesliders (see Figure \@ref(fig:ggplotly-rangeslider)).
* `style()` for modifying data-level attributes, which can be used to:
* Control the tooltip content and styling (see Section \@ref(tooltip-text-ggplotly)).
* Turn hovering on/off (see Figure \@ref(fig:style-hoverinfo)).
* Add marker points to lines (e.g., `style(p, mode = "markers+lines")`).
* `config()` for modifying the plot configuration, which can be used to:
* Control the modebar (see Chapter \@ref(control-modebar)).
* Change the default language (see Chapter \@ref(locales)).
* Enable LaTeX rendering (see Chapter \@ref(mathjax)).
* Enable editable shapes (see Chapter \@ref(editing-views)).
\index{ggplotly()@\texttt{ggplotly()}!dynamicTicks@\texttt{dynamicTicks}}
\index{ggplotly()@\texttt{ggplotly()}!layerData@\texttt{layerData}}
In addition to using the functions above to modify `ggplotly()`'s return value, the `ggplotly()` function itself provides some arguments for controlling that return value. In this chapter, we'll see a couple of them:
* `dynamicTicks`: should plotly.js dynamically generate axis tick labels? Dynamic ticks are useful for updating ticks in response to zoom/pan interactions; however, they cannot always reproduce labels as they would appear in the static ggplot2 image (see Figure \@ref(fig:ggplotly-rangeslider)).
* `layerData`: which **ggplot2** layer's data should be returned (see Figure \@ref(fig:se-annotations))?
## Modifying layout
Any aspect of a **plotly** object's layout can be modified^[Or, in the case of cumulative attributes, like `shapes`, `images`, `annotations`, etc, these items will be added to the existing items.] via the `layout()` function. By default, since it doesn't always make sense to compare values, `ggplotly()` will usually set `layout.hovermode='closest'`. As shown in Figure \@ref(fig:ggplotly-rangeslider), when we have multiple y-values of interest at a specific x-value, it can be helpful to set `layout.hovermode='x'`. Moreover, for a long time series graph like this, zooming in on the x-axis can be useful; `dynamicTicks` allows plotly.js to handle the generation of axis ticks and the `rangeslider()` allows us to zoom on the x-axis without losing the global context.
\indexc{rangeslider()}
\index{layout()@\texttt{layout()}!hovermode@\texttt{hovermode}}
```r
library(babynames)
nms <- filter(babynames, name %in% c("Sam", "Alex"))
p <- ggplot(nms) +
geom_line(aes(year, prop, color = sex, linetype = name))
ggplotly(p, dynamicTicks = TRUE) %>%
rangeslider() %>%
layout(hovermode = "x")
```
```{r ggplotly-rangeslider, echo = FALSE, fig.cap = "(ref:ggplotly-rangeslider)"}
include_vimeo("325298724")
```
Since a single **plotly** object can only have one layout, modifying the layout of `ggplotly()` is fairly easy, but it's trickier to modify the data underlying the graph.
## Modifying data
As mentioned previously, `ggplotly()` translates each ggplot2 layer into one or more plotly.js traces. In this translation, it is forced to make a number of assumptions about trace attribute values that may or may not be appropriate for the use case. To demonstrate, consider Figure \@ref(fig:simple-scatterplot), which shows hover information for the points, the fitted line, and the confidence band. How could we make it so that hover information is only displayed for the points and not for the fitted line and confidence band?
\index{ggplotly()@\texttt{ggplotly()}!ggplot2!geom\_point()@\texttt{geom\_point()}}
\index{ggplotly()@\texttt{ggplotly()}!ggplot2!geom\_smooth()@\texttt{geom\_smooth()}}
```r
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() + geom_smooth()
ggplotly(p)
```
```{r simple-scatterplot, echo=FALSE, fig.cap="(ref:simple-scatterplot)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/simple-scatterplot.html"'}
knitr::include_graphics("images/simple-scatterplot.png")
```
The **ggplot2** package doesn't provide an API for interactive features, but by changing the [hoverinfo](https://plot.ly/r/reference/#scatter-hoverinfo) attribute to `"none"`, we can turn off hover for the relevant traces. This sort of task (i.e., modifying trace attribute values) is best achieved through the `style()` function. Before using it, you may want to study the underlying traces with `plotly_json()` which uses the **listviewer** package to display a convenient interactive view of the JSON object sent to plotly.js [@listviewer]. By clicking on the arrow next to the data element, you can see the traces (data) behind the plot. As shown in Figure \@ref(fig:listviewer), we have three traces: one for the `geom_point()` layer and two for the `geom_smooth()` layer.
```r
plotly_json(p)
```
```{r listviewer, echo = FALSE, fig.cap = "(ref:listviewer)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/listviewer.html"'}
knitr::include_graphics("images/listviewer.png")
```
This output indicates that the fitted line and confidence band are implemented in the 2nd and 3rd trace of the plotly object, so to turn off the hover of those traces:
\indexc{style()}
```r
style(p, hoverinfo = "none", traces = 2:3)
```
```{r style-hoverinfo, echo = FALSE, fig.cap = "(ref:style-hoverinfo)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/style-hoverinfo.html"'}
knitr::include_graphics("images/style-hoverinfo.png")
```
## Leveraging statistical output
Since `ggplotly()` returns a plotly object, and **plotly** objects can have data attached to them, it attaches data from **ggplot2** layer(s) (either before or after summary statistics have been applied). Furthermore, since each ggplot layer owns a data frame, it is useful to have some way to specify the particular layer of data of interest, which is done via the `layerData` argument in `ggplotly()`. Also, when a particular layer applies a summary statistic (e.g., `geom_bin()`), or applies a statistical model (e.g., `geom_smooth()`) to the data, it might be useful to access the output of that transformation, which is the point of the `originalData` argument in `ggplotly()`.
```{r}
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() + geom_smooth()
p %>%
ggplotly(layerData = 2, originalData = FALSE) %>%
plotly_data()
```
The data shown above is the data ggplot2 uses to actually draw the fitted values (as a line) and standard error bounds (as a ribbon). Figure \@ref(fig:se-annotations) leverages this data to add additional information about the model fit; in particular, it adds vertical lines and annotations at the x-values that are associated with the highest and lowest amount uncertainty in the fitted values. Producing a plot like this with **ggplot2** would be impossible using `geom_smooth()` alone.^[It could be recreated by fitting the model via `loess()`, obtaining the fitted values and standard error with `predict()`, and feeding those results into `geom_line()`/`geom_ribbon()`/`geom_text()`/`geom_segment()`, but that process is much more onerous.] Providing a simple visual clue like this can help combat visual misperceptions of uncertainty bands due to the sine illusion [@sine-illusion].
\index{Data-plot-pipeline}
\index{Data-plot-pipeline!add\_fun()@\texttt{add\_fun()}}
\index{add\_annotations()@\texttt{add\_annotations()}!Data coordinates}
\index{add\_trace()@\texttt{add\_trace()}!add\_segments()@\texttt{add\_segments()}}
\index{ggplotly()@\texttt{ggplotly()}!layerData@\texttt{layerData}}
```r
p %>%
ggplotly(layerData = 2, originalData = FALSE) %>%
add_fun(function(p) {
p %>% slice(which.max(se)) %>%
add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
add_annotations("Maximum uncertainty", ax = 60)
}) %>%
add_fun(function(p) {
p %>% slice(which.min(se)) %>%
add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
add_annotations("Minimum uncertainty")
})
```
```{r se-annotations, echo = FALSE, fig.cap = "(ref:se-annotations)", out.extra = if (knitr::is_html_output()) 'data-url="/interactives/se-annotations.html"'}
knitr::include_graphics("images/se-annotations.svg")
```
In addition to leveraging output from `StatSmooth`, it is sometimes useful to leverage output of other statistics, especially for annotation purposes. Figure \@ref(fig:StatBin) leverages the output of `StatBin` to add annotations to a stacked bar chart. Annotation is primarily helpful for displaying the heights of bars in a stacked bar chart, since decoding the heights of bars is a fairly difficult perceptual task [@graphical-perception]. As a result, it is much easier to compare bar heights representing the proportion of diamonds with a given clarity across various diamond cuts.
\index{ggplotly()@\texttt{ggplotly()}!ggplot2!geom\_bar()@\texttt{geom\_bar()}}
\index{add\_trace()@\texttt{add\_trace()}!add\_text()@\texttt{add\_text()}}
```r
p <- ggplot(diamonds, aes(cut, fill = clarity)) +
geom_bar(position = "fill")
ggplotly(p, originalData = FALSE) %>%
mutate(ydiff = ymax - ymin) %>%
add_text(
x = ~x, y = ~(ymin + ymax) / 2,
text = ~ifelse(ydiff > 0.02, round(ydiff, 2), ""),
showlegend = FALSE, hoverinfo = "none",