-
Notifications
You must be signed in to change notification settings - Fork 18
/
interactive-graphics.qmd
executable file
·797 lines (643 loc) · 22.6 KB
/
interactive-graphics.qmd
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
# 交互图形 {#sec-interactive-graphics}
```{r}
#| echo: false
source("_common.R")
```
```{css}
#| echo: false
.modebar {
display: none !important;
}
```
在之前的数据探索章节介绍了 **ggplot2** 包,本章将介绍 **plotly** 包,绘制交互图形,包含基础元素、常用图形和技巧,沿用日志提交数据和 Base R 内置的斐济及周边地震数据。写作上,仍然以一个数据串联尽可能多的小节,从 **ggplot2** 包到 **plotly** 包,将介绍其间的诸多联系,以便读者轻松掌握。
## 基础元素 {#sec-interactive-elements}
### 图层 {#sec-plotly-layer}
**plotly** 包封装了许多图层函数,可以绘制各种各样的统计图形,见下 @tbl-plotly-layers 。
```{r}
#| eval: false
#| echo: false
library(plotly, warn.conflicts = FALSE)
knitr::kable(matrix(grep("add_*", x = ls("package:plotly"), value = T), ncol = 3),
col.names = c("A", "B", "C"), caption = "图层", format = "pipe"
)
```
| | | |
|:----------------|:-----------------------|:---------------|
| add_annotations | add_histogram | add_polygons |
| add_area | add_histogram2d | add_ribbons |
| add_bars | add_histogram2dcontour | add_scattergeo |
| add_boxplot | add_image | add_segments |
| add_choropleth | add_lines | add_sf |
| add_contour | add_markers | add_surface |
| add_data | add_mesh | add_table |
| add_fun | add_paths | add_text |
| add_heatmap | add_pie | add_trace |
: **plotly** 包可以绘制丰富的统计图形 {#tbl-plotly-layers}
下面以散点图为例,使用方式非常类似 **ggplot2** 包,函数 `plot_ly()` 类似 `ggplot()`,而函数 `add_markers()` 类似 `geom_point()`,效果如 @fig-plotly-markers 所示。
```{r}
#| label: fig-plotly-markers-html
#| eval: false
#| echo: true
# https://plotly.com/r/reference/scatter/
plotly::plot_ly(data = quakes, x = ~long, y = ~lat) |>
plotly::add_markers()
```
```{r}
#| label: fig-plotly-markers
#| fig-cap: "默认风格的简单散点图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-formula.png")
```
或者使用函数 `add_trace()`,层层添加图形元素,效果和上 @fig-plotly-markers 是一样的。
```{r}
#| label: fig-plotly-trace
#| eval: false
plotly::plot_ly(data = quakes, x = ~long, y = ~lat) |>
plotly::add_trace(type = "scatter", mode = "markers")
```
::: callout-tip
**plotly** 包的函数 `plot_ly()` 又与 **ggplot2** 包中函数 `qplot()` 类似,可以将大部分设置塞进去。
```{r}
#| label: fig-plotly-qplot
#| eval: false
plotly::plot_ly(
data = quakes, x = ~long, y = ~lat,
type = "scatter", mode = "markers"
)
```
所以,总的来说, `add_markers()` 、`add_trace(type = "scatter", mode = "markers")` 和 `plot_ly(type = "scatter", mode = "markers")` 是等价的。
:::
### 配色 {#sec-plotly-color}
在 @fig-plotly-markers 的基础上,将颜色映射到震级变量上。
```{r}
#| label: fig-plotly-color
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "给散点图配色"
plotly::plot_ly(data = quakes, x = ~long, y = ~lat) |>
plotly::add_markers(color = ~mag)
```
### 刻度 {#sec-plotly-scale}
东经和南纬
```{r}
#| label: fig-plotly-scale
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "设置刻度及标签"
plotly::plot_ly(data = quakes, x = ~long, y = ~lat) |>
plotly::add_markers(color = ~mag) |>
plotly::layout(
xaxis = list(title = "经度", ticksuffix = 'E'),
yaxis = list(title = "纬度", ticksuffix = 'S')
)
```
### 标签 {#sec-plotly-label}
添加横轴、纵轴以及主副标题
```{r}
#| label: fig-plotly-label
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "添加各处标题"
plotly::plot_ly(
data = quakes, x = ~long, y = ~lat,
marker = list(
color = ~mag,
colorscale = "Viridis",
colorbar = list(title = list(text = "震级"))
)
) |>
plotly::add_markers() |>
plotly::layout(
xaxis = list(title = "经度"),
yaxis = list(title = "纬度"),
title = "斐济及其周边地区的地震活动"
)
```
### 主题 {#sec-plotly-theme}
plotly 内置了一些主题风格
```{r}
#| label: fig-plotly-theme
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "设置主题风格"
plotly::plot_ly(
data = quakes, x = ~long, y = ~lat,
marker = list(
color = ~mag,
colorscale = "Viridis",
colorbar = list(title = list(text = "震级"))
)
) |>
plotly::add_markers() |>
plotly::layout(
xaxis = list(title = "经度"),
yaxis = list(title = "纬度"),
title = "斐济及其周边地区的地震活动"
)
```
### 字体 {#sec-plotly-font}
### 图例 {#sec-plotly-legend}
## 常用图形 {#sec-plotly-common-graphics}
### 散点图 {#sec-plotly-scatter}
**plotly** 包支持绘制许多常见的散点图,从直角坐标系 `scatter` 到极坐标系 `scatterpolar` 和地理坐标系 `scattergeo`,从二维平面 `scatter` 到三维空间 `scatter3d`,借助 WebGL 可以渲染大规模的数据点 `scattergl`。
| 类型 | 名称 |
|:-----------------|:------------------------------|
| `scatter` | 二维平面散点图 |
| `scatter3d` | 三维立体散点图 |
| `scattergl` | 散点图(WebGL 版) |
| `scatterpolar` | 极坐标下散点图 |
| `scatterpolargl` | 极坐标下散点图(WebGL 版) |
| `scattergeo` | 地理坐标下散点图 |
| `scattermapbox` | 地理坐标下散点图(MapBox 版) |
| `scattercarpet` | 地毯图 |
| `scatterternary` | 三元图 |
: plotly 包支持绘制的散点图类型 {#tbl-plotly-scatter}
@fig-scatter 展示斐济及其周边的地震分布
```{r}
#| label: fig-scatter-html
#| eval: false
#| echo: true
plotly::plot_ly(
data = quakes, x = ~long, y = ~lat,
type = "scatter", mode = "markers"
) |>
plotly::layout(
xaxis = list(title = "经度"),
yaxis = list(title = "纬度")
)
```
```{r}
#| label: fig-scatter
#| fig-cap: "普通散点图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-scatter.png")
```
### 柱形图 {#sec-plotly-bar}
```{r}
#| echo: false
svn_trunk_log <- readRDS(file = "data/svn-trunk-log-2022.rds")
svn_trunk_log <- within(svn_trunk_log, {
# 提取日期、月份、年份、星期、第几周、第几天等时间成分
year <- as.integer(format(stamp, "%Y"))
date <- format(stamp, format = "%Y-%m-%d", tz = "UTC")
month <- format(stamp, format = "%m", tz = "UTC")
hour <- format(stamp, format = "%H", tz = "UTC")
week <- format(stamp, format = "%U", tz = "UTC")
wday <- format(stamp, format = "%a", tz = "UTC")
nday <- format(stamp, format = "%j", tz = "UTC")
})
trunk_year <- aggregate(data = svn_trunk_log, revision ~ year, FUN = length)
```
```{r}
#| label: fig-plotly-bar
#| fig-cap: "柱形图"
#| eval: !expr knitr::is_html_output(excludes = 'epub')
# https://plotly.com/r/reference/bar/
plotly::plot_ly(
data = trunk_year, x = ~year, y = ~revision, type = "bar"
) |>
plotly::layout(
xaxis = list(title = "年份"),
yaxis = list(title = "代码提交量")
)
```
### 曲线图 {#sec-plotly-line}
```{r}
#| label: fig-plotly-curve
#| fig-cap: "曲线图"
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::plot_ly(
data = trunk_year, x = ~year, y = ~revision, type = "scatter",
mode = "markers+lines", line = list(shape = "spline")
) |>
plotly::layout(
xaxis = list(title = "年份"),
yaxis = list(title = "代码提交量")
)
```
### 直方图 {#sec-plotly-hist}
地震次数随震级的分布变化,下 @fig-quakes-mag 为频数分布图
```{r}
#| label: fig-quakes-mag-html
#| eval: false
#| echo: true
# https://plotly.com/r/reference/histogram/
plotly::plot_ly(quakes, x = ~mag, type = "histogram") |>
plotly::layout(
xaxis = list(title = "震级"),
yaxis = list(title = "次数")
)
```
```{r}
#| label: fig-quakes-mag
#| fig-cap: "地震震级的频数分布图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-quakes-mag.png")
```
地震震级的概率分布,下 @fig-quakes-mag-prob 为频率分布图
```{r}
#| label: fig-quakes-mag-prob-html
#| eval: false
#| echo: true
plotly::plot_ly(
data = quakes, x = ~mag, type = "histogram",
histnorm = "probability",
marker = list(
color = "lightblue",
line = list(color = "white", width = 2)
)
) |>
plotly::layout(
xaxis = list(title = "震级"),
yaxis = list(title = "频率")
)
```
```{r}
#| label: fig-quakes-mag-prob
#| fig-cap: "地震震级的频率分布图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-quakes-mag-prob.png")
```
`histnorm = "probability"` 意味着纵轴表示频率,即每个窗宽下地震次数占总地震次数的比例。地震常常发生在地下,不同的深度对应着不同的地质构造、不同的地震成因,下 @fig-quakes-depth-hist 展示海平面下不同深度的地震震级分布。
```{r}
quakes$depth_bin <- cut(quakes$depth, breaks = 150 * 0:5)
```
```{r}
#| label: fig-quakes-depth-hist-html
#| eval: false
#| echo: true
plotly::plot_ly(quakes,
x = ~mag, colors = "viridis",
color = ~depth_bin, type = "histogram"
) |>
plotly::layout(
xaxis = list(title = "震级"),
yaxis = list(title = "次数")
)
```
```{r}
#| label: fig-quakes-depth-hist
#| fig-cap: "地震震级的频率分布图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-quakes-depth-hist.png")
```
### 箱线图 {#sec-plotly-boxplot}
```{r}
#| label: fig-quakes-depth-box
#| fig-cap: "不同深度下地震震级的分布"
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::plot_ly(quakes,
x = ~depth_bin, y = ~mag, colors = "viridis",
color = ~depth_bin, type = "box"
) |>
plotly::layout(
xaxis = list(title = "深度"),
yaxis = list(title = "震级")
)
```
```{r}
#| label: fig-quakes-depth-violin
#| fig-cap: "不同深度下地震震级的分布"
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::plot_ly(quakes,
x = ~depth_bin, y = ~mag, split = ~depth_bin,
type = "violin", color = ~depth_bin, colors = "viridis",
box = list(visible = TRUE),
meanline = list(visible = TRUE)
) |>
plotly::layout(
xaxis = list(title = "深度"),
yaxis = list(title = "震级")
)
```
### 热力图 {#sec-plotly-densitymap}
plotly 整合了开源的 [Mapbox GL JS](https://github.com/mapbox/mapbox-gl-js),可以使用 Mapbox 提供的瓦片地图服务(Mapbox Tile Maps),对空间点数据做核密度估计,展示热力分布,如 @fig-densitymap 所示。图左上角为所罗门群岛(Solomon Islands)、瓦努阿图(Vanuatu)和新喀里多尼亚(New Caledonia),图下方为新西兰北部的威灵顿(Wellington)和奥克兰(Auckland),图中部为斐济(Fiji)。
```{r}
#| label: fig-densitymap-html
#| eval: false
#| echo: true
plotly::plot_ly(
data = quakes, lat = ~lat, lon = ~long, radius = 10,
type = "densitymapbox", coloraxis = "coloraxis"
) |>
plotly::layout(
mapbox = list(
style = "stamen-terrain", zoom = 3,
center = list(lon = 180, lat = -25)
),
coloraxis = list(colorscale = "Viridis")
)
```
```{r}
#| label: fig-densitymap
#| fig-cap: "空间点数据的核密度估计"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-densitymap.png")
```
图中设置瓦片地图的风格 `style` 为 `"stamen-terrain"`,还可以使用其他开放的栅格瓦片地图服务,比如 `"open-street-map"` 和 `"carto-positron"`。如果使用 MapBox 提供的矢量瓦片地图服务,则需要访问令牌 Mapbox Access Token。图中设置中心坐标 `center` 以及缩放倍数 `zoom`,目的是突出图片中的数据区域。设置调色板 Viridis 展示热力分布,黄色团块的地方表示地震频次高。
### 面量图 {#sec-plotly-choropleth-maps}
在之前我们介绍过用 ggplot2 绘制地区分布图,实际上,地区分布图还有别名,如围栏图、面量图等。本节使用 plotly 绘制交互式的地区分布图,如 @fig-choropleth-map 所示。
```{r}
#| label: fig-choropleth-map-html
#| eval: false
#| echo: true
# https://plotly.com/r/reference/choropleth/
dat <- data.frame(state.x77,
stats = rownames(state.x77),
stats_abbr = state.abb
)
# 绘制图形
plotly::plot_ly(
data = dat,
type = "choropleth",
locations = ~stats_abbr,
locationmode = "USA-states",
colorscale = "Viridis",
colorbar = list(title = list(text = "人均收入")),
z = ~Income
) |>
plotly::layout(
geo = list(scope = "usa"),
title = "1974年美国各州的人均收入"
)
```
```{r}
#| label: fig-choropleth-map
#| fig-cap: "1974 年美国各州的人均收入"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-choropleth-map.png")
```
### 动态图 {#sec-plotly-animation}
本节参考 plotly 包的官方示例[渐变动画](https://plotly.com/r/cumulative-animations/),数据来自 SVN 代码提交日志,统计 Martin Maechler 和 Brian Ripley 的年度代码提交量,他们是 R Core Team 非常重要的两位成员,长期参与维护 R 软件及社区。下图展示 1999-2022 年 Martin Maechler 和 Brian Ripley 的代码提交量变化。
```{r}
#| label: fig-plotly-animation
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "1999-2022 年 Martin Maechler 和 Brian Ripley 的代码提交量变化"
# https://plotly.com/r/animations/
trunk_year_author <- aggregate(data = svn_trunk_log, revision ~ year + author, FUN = length)
# https://plotly.com/r/cumulative-animations/
accumulate_by <- function(dat, var) {
var <- lazyeval::f_eval(f = var, data = dat)
lvls <- plotly:::getLevels(var)
dats <- lapply(seq_along(lvls), function(x) {
cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})
dplyr::bind_rows(dats)
}
subset(trunk_year_author, year >= 1999 & author %in% c("ripley", "maechler")) |>
accumulate_by(~year) |>
plotly::plot_ly(
x = ~year, y = ~revision, split = ~author,
frame = ~frame, type = "scatter", mode = "lines",
line = list(simplyfy = F)
) |>
plotly::layout(
xaxis = list(title = "年份"),
yaxis = list(title = "代码提交量")
) |>
plotly::animation_opts(
frame = 100, transition = 0, redraw = FALSE
) |>
plotly::animation_button(
visible = TRUE, # 显示播放按钮
label = "播放", # 按钮文本
font = list(color = "gray")# 文本颜色
) |>
plotly::animation_slider(
currentvalue = list(
prefix = "年份 ",
xanchor = "right",
font = list(color = "gray", size = 30)
)
)
```
[**lazyeval**](https://github.com/hadley/lazyeval) 的非标准计算采用 Base R 实现,目前,已经可以被 [**rlang**](https://github.com/r-lib/rlang/) 替代。
## 常用技巧 {#sec-plotly-common-tricks}
### 数学公式 {#sec-plotly-formula}
正态分布的概率密度函数形式如下:
$$
\begin{aligned}
& f(x;\mu,\sigma^2) = \frac{1}{\sqrt{2\pi}\sigma}\exp\{-\frac{(x -\mu)^2}{2\sigma^2}\}
\end{aligned}
$$
下图展示两个正态分布,分别是 $\mathcal{N}(3, 1^2)$ 和 $\mathcal{N}(2, 1.5^2)$ 。函数 `plotly::TeX()` 包裹 LaTeX 书写的数学公式,**plotly** 包调用 [MathJax](https://www.mathjax.org/) 库渲染图中的公式符号。
```{r}
#| eval: false
#| code-fold: true
x <- seq(from = -4, to = 8, length.out = 193)
y1 <- dnorm(x, mean = 3, sd = 1)
y2 <- dnorm(x, mean = 2, sd = 1.5)
plotly::plot_ly(
x = x, y = y1, type = "scatter", mode = "lines",
fill = "tozeroy", fillcolor = "rgba(0, 204, 102, 0.2)",
text = ~ paste0(
"x:", x, "<br>",
"y:", round(y1, 3), "<br>"
),
hoverinfo = "text",
name = plotly::TeX("\\mathcal{N}(3,1^2)"),
line = list(shape = "spline", color = "#009B95")
) |>
plotly::add_trace(
x = x, y = y2, type = "scatter", mode = "lines",
fill = "tozeroy", fillcolor = "rgba(51, 102, 204, 0.2)",
text = ~ paste0(
"x:", x, "<br>",
"y:", round(y2, 3), "<br>"
),
hoverinfo = "text",
name = plotly::TeX("\\mathcal{N}(2, 1.5^2)"),
line = list(shape = "spline", color = "#403173")
) |>
plotly::layout(
xaxis = list(showgrid = F, title = plotly::TeX("x")),
yaxis = list(showgrid = F, title = plotly::TeX("f(x)")),
legend = list(x = 0.8, y = 1, orientation = "v")
) |>
plotly::config(mathjax = "cdn", displayModeBar = FALSE)
```
```{r}
#| label: fig-plotly-formula
#| fig-cap: "设置数学公式"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-formula.png")
```
### 动静转化 {#sec-plotly-ggplotly}
在出版书籍,发表期刊文章,打印纸质文稿等场景中,需要将交互图形导出为静态图形,再插入到正文之中。
```{r}
#| label: fig-ggplot-to-ggplotly
#| fig-cap: "ggplot2 绘制的静态图形"
#| fig-showtext: true
library(ggplot2)
p <- ggplot(data = quakes, aes(x = long, y = lat)) +
geom_point()
p
```
将 **ggplot2** 包绘制的散点图转化为交互式的散点图,只需调用 **plotly** 包的函数 `ggplotly()`。
```{r}
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::ggplotly(p)
```
当使用配置函数 `config()` 设置参数选项 `staticPlot = TRUE`,可将原本交互式的动态图形转为非交互式的静态图形。
```{r}
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::ggplotly(p) |>
plotly::config(staticPlot = TRUE)
```
::: callout-tip
函数 `style()` 设置动态点的注释,比如点横纵坐标、坐标文本,以及整个注释标签的样式,如背景色。
```{r}
#| eval: !expr knitr::is_html_output(excludes = 'epub')
plotly::ggplotly(p, dynamicTicks = "y") |>
plotly::style(hoveron = "points", hoverinfo = "x+y+text",
hoverlabel = list(bgcolor = "white"))
```
:::
orca (Open-source Report Creator App) 软件针对 **plotly.js** 库渲染的图形具有很强的导出功能,[安装 orca](https://github.com/plotly/orca#installation) 后,`plotly::orca()` 函数可以将基于 **htmlwidgets** 的 **plotly** 图形对象导出为 PNG、PDF 和 SVG 等格式的高质量静态图片。
```{r}
#| eval: false
# orca
plotly::orca(p, "plotly-quakes.svg")
# kaleido
plotly::save_image(p, "plotly-quakes.svg")
```
### 坐标系统 {#sec-plotly-coord}
quakes 是一个包含空间位置的数据集,plotly 的 `scattergeo` 图层 针对空间数据提供多边形矢量边界地图数据,支持设定坐标参考系。下 @fig-scattergeo 增加了地震震级维度,在空间坐标参考系下绘制散点。
```{r}
#| label: fig-scattergeo-html
#| eval: false
#| echo: true
plotly::plot_ly(
data = quakes,
lon = ~long, lat = ~lat,
type = "scattergeo", mode = "markers",
text = ~ paste0(
"站点:", stations, "<br>",
"震级:", mag
),
marker = list(
color = ~mag, colorscale = "Viridis",
size = 10, opacity = 0.8,
line = list(color = "white", width = 1)
)
) |>
plotly::layout(geo = list(
showland = TRUE,
landcolor = plotly::toRGB("gray95"),
countrycolor = plotly::toRGB("gray85"),
subunitcolor = plotly::toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5,
lonaxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(160, 190),
dtick = 5
),
lataxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(-40, -10),
dtick = 5
)
))
```
```{r}
#| label: fig-scattergeo
#| fig-cap: "空间点数据图"
#| out-width: 80%
#| echo: false
knitr::include_graphics(path = "images/plotly-scattergeo.png")
```
### 添加水印 {#sec-plotly-watermark}
在图片右下角添加水印图片
```{r}
#| label: fig-watermark
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "添加水印图片"
plotly::plot_ly(quakes,
x = ~long, y = ~lat, color = ~mag,
type = "scatter", mode = "markers"
) |>
plotly::config(staticPlot = TRUE) |>
plotly::layout(
images = list( # 水印图片
source = "https://images.plot.ly/language-icons/api-home/r-logo.png",
xref = "paper", # 页面参考
yref = "paper",
x = 0.90, # 横坐标
y = 0.20, # 纵坐标
sizex = 0.2, # 长度
sizey = 0.2, # 宽度
opacity = 0.5 # 透明度
)
)
```
### 多图布局 {#sec-plotly-subplot}
将两个图形做上下排列
```{r}
#| label: fig-tagList
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "上下布局"
p1 <- plotly::plot_ly(
data = trunk_year, x = ~year, y = ~revision, type = "bar"
) |>
plotly::layout(
xaxis = list(title = "年份"),
yaxis = list(title = "代码提交量")
)
p2 <- plotly::plot_ly(
data = trunk_year, x = ~year, y = ~revision, type = "scatter",
mode = "markers+lines", line = list(shape = "spline")
) |>
plotly::layout(
xaxis = list(title = "年份"),
yaxis = list(title = "代码提交量")
)
htmltools::tagList(p1, p2)
```
plotly 包提供的函数 `subplot()` 专门用于布局排列,下图的上下子图共享 x 轴。
```{r}
#| label: fig-subplot-1
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "上下布局"
plotly::subplot(plotly::style(p1, showlegend = FALSE),
plotly::style(p2, showlegend = FALSE),
nrows = 2, margin = 0.05, shareX = TRUE, titleY = TRUE)
```
下图展示更加灵活的布局形式,嵌套使用布局函数 `subplot()` 实现。
```{r}
#| label: fig-subplot-2
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "灵活布局"
p11 <- plotly::subplot(plotly::style(p1, showlegend = FALSE),
plotly::style(p2, showlegend = FALSE),
nrows = 1, margin = 0.05, shareY = TRUE, titleX = TRUE
)
plotly::subplot(p11,
plotly::style(p2, showlegend = FALSE),
nrows = 2, margin = 0.05, shareY = FALSE, titleX = FALSE
)
```
### 图表联动 {#sec-plotly-crosstalk}
**crosstalk** 包可将 **plotly** 包绘制的图形和 **DT** 包制作的表格联动起来。**plotly** 绘制交互图形,在图形上用套索工具筛选出来的数据显示在表格中。
```{r}
#| label: fig-crosstalk
#| eval: !expr knitr::is_html_output(excludes = 'epub')
#| fig-cap: "图表联动"
library(crosstalk)
# quakes 数据变成可共享的
quakes_sd <- SharedData$new(quakes)
# 绘制交互图形
p <- plotly::plot_ly(quakes_sd, x = ~long, y = ~lat) |>
plotly::add_markers() |>
plotly::highlight(on = "plotly_selected", off = "plotly_deselect")
# 制作表格
d <- DT::datatable(quakes_sd, options = list(dom = "tp"))
# 将图表组合一起展示
bscols(list(p, d))
```