-
Notifications
You must be signed in to change notification settings - Fork 253
/
chapter_12.html
930 lines (696 loc) · 30.8 KB
/
chapter_12.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>chapter_12.knit</title>
<meta charset="utf-8" />
<meta name="author" content="Pac_B" />
<script src="libs/header-attrs-2.26/header-attrs.js"></script>
<link href="libs/remark-css-0.0.1/default.css" rel="stylesheet" />
<link href="libs/panelset-0.2.6/panelset.css" rel="stylesheet" />
<script src="libs/panelset-0.2.6/panelset.js"></script>
<script src="libs/htmlwidgets-1.6.4/htmlwidgets.js"></script>
<link href="libs/datatables-css-0.0.0/datatables-crosstalk.css" rel="stylesheet" />
<script src="libs/datatables-binding-0.32/datatables.js"></script>
<script src="libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<link href="libs/dt-core-1.13.6/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="libs/dt-core-1.13.6/css/jquery.dataTables.extra.css" rel="stylesheet" />
<script src="libs/dt-core-1.13.6/js/jquery.dataTables.min.js"></script>
<link href="libs/crosstalk-1.2.1/css/crosstalk.min.css" rel="stylesheet" />
<script src="libs/crosstalk-1.2.1/js/crosstalk.min.js"></script>
<link rel="stylesheet" href="css/Custumed_Style.css" type="text/css" />
<link rel="stylesheet" href="css/zh-CN.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle
<span style="font-size: 60px;">**第十二章**</span> <br>
<span style="font-size: 50px;">如何得到可发表的图像</span> <br>
<span style="font-size: 50px;">数据可视化进阶</span> <br>
<span style="font-size: 30px;">胡传鹏</span> <br>
<span style="font-size: 20px;"> </span> <br>
<span style="font-size: 30px;">2024-05-22</span> <br>
<span style="font-size: 20px;"> Made with Rmarkdown</span> <br>
<style type="text/css">
/* ---- extra.css ---- */
.bigfont {
font-size: 30px;
}
.size5{
font-size: 20px;
}
.tit_font{
font-size: 60px;
}
</style>
---
<br>
<br>
<br>
<br>
.pull-left[
# 为什么要作图?
- “一图胜千言”
- 信息传递的直观性
# 用什么做图?
- ggplot 2
]
.pull-right[
# 怎么画好一张图?
- 明确想要得到的图像
- “信达雅”
- 信息量
- 逻辑性
- 美观(简洁、对称、和谐)
]
---
.panelset[
.panel[.panel-name[Packages]
```r
if (!requireNamespace('pacman', quietly = TRUE)) {
install.packages('pacman')
}
pacman::p_load(
# 本节课需要用到的 packages
here, tidyverse, reshape, bruceR, ggplot2, patchwork, magick,
# 生成课件
xaringan, xaringanthemer, xaringanExtra, knitr)
options(scipen=99999,digits = 5)
```
.panel[.panel-name[trial data]
```r
df.match.trial <- bruceR::import(here::here('data','match','match_raw.csv')) %>%
tidyr::extract(Shape,
into = c('Valence', 'Identity'),
regex = '(moral|immoral)(Self|Other)',
remove = FALSE) %>% #将Shape列分为两列
dplyr::mutate(Valence = factor(Valence, levels = c('moral','immoral'), labels = c('moral','immoral')),
Identity = factor(Identity, levels = c('Self','Other'), labels = c('Self','Other'))) %>%
dplyr::filter(ACC == 0 | ACC == 1,
RT >= 0.2 & RT <= 1.5,
Match == 'match',
(!Sub %in% c(7302,7303,7338)))
```
<div class="datatables html-widget html-fill-item" id="htmlwidget-a51952170b90a44611db" style="width:100%;height:auto;"></div>
<script type="application/json" data-for="htmlwidget-a51952170b90a44611db">{"x":{"filter":"none","vertical":false,"data":[["1","2","3","4"],["06-May-2018_14:45:42","06-May-2018_14:45:44","06-May-2018_14:45:50","06-May-2018_14:45:53"],["Exp","Exp","Exp","Exp"],[7304,7304,7304,7304],[25,25,25,25],["female","female","female","female"],["R","R","R","R"],[1,1,1,1],[1,1,1,1],[3,4,7,8],["moralOther","immoralOther","moralSelf","immoralOther"],["moral","immoral","moral","immoral"],["Other","Other","Self","Other"],["moralOther","immoralOther","moralSelf","immoralOther"],["match","match","match","match"],["n","n","n","n"],["n","m","n","m"],[1,0,1,0],[0.8167,0.8728,0.4951,0.8713]],"container":"<table class=\"display\">\n <thead>\n <tr>\n <th> <\/th>\n <th>Date<\/th>\n <th>Prac<\/th>\n <th>Sub<\/th>\n <th>Age<\/th>\n <th>Sex<\/th>\n <th>Hand<\/th>\n <th>Block<\/th>\n <th>Bin<\/th>\n <th>Trial<\/th>\n <th>Shape<\/th>\n <th>Valence<\/th>\n <th>Identity<\/th>\n <th>Label<\/th>\n <th>Match<\/th>\n <th>CorrResp<\/th>\n <th>Resp<\/th>\n <th>ACC<\/th>\n <th>RT<\/th>\n <\/tr>\n <\/thead>\n<\/table>","options":{"columnDefs":[{"className":"dt-right","targets":[3,4,7,8,9,17,18]},{"orderable":false,"targets":0},{"name":" ","targets":0},{"name":"Date","targets":1},{"name":"Prac","targets":2},{"name":"Sub","targets":3},{"name":"Age","targets":4},{"name":"Sex","targets":5},{"name":"Hand","targets":6},{"name":"Block","targets":7},{"name":"Bin","targets":8},{"name":"Trial","targets":9},{"name":"Shape","targets":10},{"name":"Valence","targets":11},{"name":"Identity","targets":12},{"name":"Label","targets":13},{"name":"Match","targets":14},{"name":"CorrResp","targets":15},{"name":"Resp","targets":16},{"name":"ACC","targets":17},{"name":"RT","targets":18}],"order":[],"autoWidth":false,"orderClasses":false}},"evals":[],"jsHooks":[]}</script>
.panel[.panel-name[subj data]
```r
df.match.subj <- df.match.trial %>%
dplyr::group_by(Sub, Identity, Valence) %>%
dplyr::summarise(RT_mean = mean(RT),
ACC_mean = mean(ACC)) %>%
dplyr::ungroup()
```
<div class="datatables html-widget html-fill-item" id="htmlwidget-d3983644fdf2df6ccfe9" style="width:100%;height:auto;"></div>
<script type="application/json" data-for="htmlwidget-d3983644fdf2df6ccfe9">{"x":{"filter":"none","vertical":false,"data":[["1","2","3","4"],[7304,7304,7304,7304],["Self","Self","Other","Other"],["moral","immoral","moral","immoral"],[0.552276,0.706672602739726,0.7493875,0.7581492957746478],[0.9866666666666667,0.821917808219178,0.8333333333333334,0.7183098591549296]],"container":"<table class=\"display\">\n <thead>\n <tr>\n <th> <\/th>\n <th>Sub<\/th>\n <th>Identity<\/th>\n <th>Valence<\/th>\n <th>RT_mean<\/th>\n <th>ACC_mean<\/th>\n <\/tr>\n <\/thead>\n<\/table>","options":{"columnDefs":[{"className":"dt-right","targets":[1,4,5]},{"orderable":false,"targets":0},{"name":" ","targets":0},{"name":"Sub","targets":1},{"name":"Identity","targets":2},{"name":"Valence","targets":3},{"name":"RT_mean","targets":4},{"name":"ACC_mean","targets":5}],"order":[],"autoWidth":false,"orderClasses":false}},"evals":[],"jsHooks":[]}</script>
.panel[.panel-name[sum data]
```r
df.match.sum <- df.match.subj %>%
dplyr::group_by(Identity, Valence) %>%
dplyr::summarise(grand_mean_RT = mean(RT_mean),
SD_RT = sd(RT_mean),
SE_RT = SD_RT/sqrt(n()-1),
grand_mean_ACC = mean(ACC_mean),
SD_ACC = sd(ACC_mean),
SE_ACC = SD_ACC/sqrt(n()-1),
n = n()) %>%
dplyr::ungroup()
```
<div class="datatables html-widget html-fill-item" id="htmlwidget-be879c504cf1844fed20" style="width:100%;height:auto;"></div>
<script type="application/json" data-for="htmlwidget-be879c504cf1844fed20">{"x":{"filter":"none","vertical":false,"data":[["1","2","3","4"],["Self","Self","Other","Other"],["moral","immoral","moral","immoral"],[0.6366372764212784,0.7150271256631987,0.6850132435574973,0.6996564845828235],[0.06334254097700114,0.06957103122069196,0.07816459938618592,0.0695041721958588],[0.01001533511349354,0.01100014589120355,0.01235890832274734,0.01098957455117302],[0.9161836748531289,0.8142527831854576,0.8440248488102073,0.828686850170307],[0.0980144792704873,0.1197130892135965,0.1095526473381531,0.1107136186340657],[0.01549744990850493,0.01892830138249502,0.01732179446448731,0.01750536014414538],[41,41,41,41]],"container":"<table class=\"display\">\n <thead>\n <tr>\n <th> <\/th>\n <th>Identity<\/th>\n <th>Valence<\/th>\n <th>grand_mean_RT<\/th>\n <th>SD_RT<\/th>\n <th>SE_RT<\/th>\n <th>grand_mean_ACC<\/th>\n <th>SD_ACC<\/th>\n <th>SE_ACC<\/th>\n <th>n<\/th>\n <\/tr>\n <\/thead>\n<\/table>","options":{"columnDefs":[{"className":"dt-right","targets":[3,4,5,6,7,8,9]},{"orderable":false,"targets":0},{"name":" ","targets":0},{"name":"Identity","targets":1},{"name":"Valence","targets":2},{"name":"grand_mean_RT","targets":3},{"name":"SD_RT","targets":4},{"name":"SE_RT","targets":5},{"name":"grand_mean_ACC","targets":6},{"name":"SD_ACC","targets":7},{"name":"SE_ACC","targets":8},{"name":"n","targets":9}],"order":[],"autoWidth":false,"orderClasses":false}},"evals":[],"jsHooks":[]}</script>
]]]]]
---
<br>
<br>
<h1 lang="en" style="font-size: 60px;">Contents</h1>
<br>
<br>
<br>
<span style="font-size: 45px;">12.1 ggplot2基础</span></center> <br>
<br>
<span style="font-size: 45px;">12.2 进阶——细节调整</span></center> <br>
<br>
<span style="font-size: 45px;">12.3 高级图片处理——magick</span></center> <br>
<br>
---
class: center, middle
<span style="font-size: 60px;">12.1 ggplot2基础</span> <br>
---
# 12.1 ggplot2基础
## 什么是ggplot
<img src="./picture/chp12/ggplot.png" width="70%" style="display: block; margin: auto;" />
---
# 12.1 ggplot2基础
## 图层叠加
<img src="./picture/chp12/gramma.png" width="65%" style="display: block; margin: auto;" />
- 和PS类似,采用图层的设计方式;
- 图层之间的叠加是靠 “+” 实现的,越往后,其图层越在上方;
- 有明确的起始(ggplot()开始)与终止;
- 有必须的图层
---
# 12.1 ggplot2基础
## 必须图层
![](./picture/chp12/required.png)
```r
# 以柱状图为例
p1 <- ggplot2::ggplot(data = df.match.sum, aes(x = Identity, y = grand_mean_RT, fill = Valence)) +
ggplot2::geom_bar(stat = "Identity",
position = "dodge") +
ggplot2::geom_errorbar(data = df.match.sum,
aes(ymin = grand_mean_RT - SE_RT, ymax = grand_mean_RT + SE_RT),
width=.1,
position = position_dodge(.9))
```
---
# 12.1 ggplot2基础
## 必须图层
```r
p1
```
<img src="chapter_12_files/figure-html/unnamed-chunk-11-1.png" width="100%" />
---
# 12.1 ggplot2基础
## 可选图层
<img src="./picture/chp12/adjust.png" width="70%" style="display: block; margin: auto;" />
```r
# 以柱状图为例
p2 <- p1 +
ggplot2::scale_y_continuous(expand=c(0, 0),
breaks = seq(0, 0.75, 0.25),
limits = c(0, 0.75)) +
ggplot2::labs(title = "Mean RT for match trials", y = "RT") +
papaja::theme_apa()
```
---
# 12.1 ggplot2基础
## 可选图层
```r
p2
```
<img src="chapter_12_files/figure-html/unnamed-chunk-14-1.png" width="100%" />
---
# 12.1 ggplot2基础
## 同理可以得到ACC的图
<img src="chapter_12_files/figure-html/unnamed-chunk-15-1.png" width="100%" />
---
# 12.1 ggplot2基础
## 可选图层
## 同时呈现两张图——方法一:分面(Facet)
.panelset[
.panel[.panel-name[Facet]
- Facet 也可以被认为是图层的一种,也是通过"+"加号叠加在原始图片上
- 可以分为一维(facet_wrap)和二维(facet_grid)两种,图示为二维
<img src="./picture/chp12/facet.png" width="40%" style="display: block; margin: auto;" />
.panel[.panel-name[Data preprocessing]
```r
df1 <- df.match.sum[,-c(6, 7, 8)]%>%
dplyr::rename(grand_mean = grand_mean_RT,
SD = SD_RT,
SE = SE_RT) %>%
dplyr::mutate(DV = "RT")
df.match.sum.long <- df.match.sum[,-c(3, 4, 5)] %>%
dplyr::rename(grand_mean = grand_mean_ACC,
SD = SD_ACC,
SE = SE_ACC) %>%
dplyr::mutate(DV = "ACC") %>%
rbind(df1,.)
rm(df1)
```
<div class="datatables html-widget html-fill-item" id="htmlwidget-cda03d1e36524a69ce81" style="width:100%;height:auto;"></div>
<script type="application/json" data-for="htmlwidget-cda03d1e36524a69ce81">{"x":{"filter":"none","vertical":false,"data":[["1","2","3"],["Self","Self","Other"],["moral","immoral","moral"],[0.6366372764212784,0.7150271256631987,0.6850132435574973],[0.06334254097700114,0.06957103122069196,0.07816459938618592],[0.01001533511349354,0.01100014589120355,0.01235890832274734],[41,41,41],["RT","RT","RT"]],"container":"<table class=\"display\">\n <thead>\n <tr>\n <th> <\/th>\n <th>Identity<\/th>\n <th>Valence<\/th>\n <th>grand_mean<\/th>\n <th>SD<\/th>\n <th>SE<\/th>\n <th>n<\/th>\n <th>DV<\/th>\n <\/tr>\n <\/thead>\n<\/table>","options":{"columnDefs":[{"className":"dt-right","targets":[3,4,5,6]},{"orderable":false,"targets":0},{"name":" ","targets":0},{"name":"Identity","targets":1},{"name":"Valence","targets":2},{"name":"grand_mean","targets":3},{"name":"SD","targets":4},{"name":"SE","targets":5},{"name":"n","targets":6},{"name":"DV","targets":7}],"order":[],"autoWidth":false,"orderClasses":false}},"evals":[],"jsHooks":[]}</script>
.panel[.panel-name[figure code]
```r
p4 <- df.match.sum.long %>%
ggplot2::ggplot(.,
aes(x = Identity,
y = grand_mean,
fill = Valence)) +
ggplot2::geom_bar(stat = "identity",
position=position_dodge(),
) +
ggplot2::geom_errorbar(aes(ymin = grand_mean-1.96*SE,
ymax = grand_mean+1.96*SE),
width = .1,
position = position_dodge(.9)) +
papaja::theme_apa() +
ggplot2::facet_wrap(~DV, scales = "free_y") +
ggplot2::labs(title = "Summary data for matching trials",
x="Identity",
y="mean")
```
.panel[.panel-name[figure]
<img src="chapter_12_files/figure-html/unnamed-chunk-20-1.png" width="85%" />
]]]]]
---
# 12.1 ggplot2基础
## 可选图层
## 同时呈现两张图——方法二:patchwork
```r
p2 + p3 + plot_layout(guides = "collect")
```
<img src="chapter_12_files/figure-html/unnamed-chunk-21-1.png" width="85%" />
---
# 12.1 ggplot2基础
## 总结
<img src="./picture/chp12/basic.png" width="80%" style="display: block; margin: auto;" />
---
# 12.1 ggplot2基础
## 总结
<img src="./picture/chp12/summary.png" width="80%" style="display: block; margin: auto;" />
.footnote[
----------------
.footfont[
注:本图来自《R语言数据可视化之美:专业图表绘制指南》
]]
---
class: center, middle
<span style="font-size: 60px;">12.2 进阶——细节调整</span> <br>
---
# 12.2 进阶——细节调整
## 问题1:可视化RT, ACC的总体趋势与个体趋势
## 目标图片1
<img src="./picture/chp12/target1.png" width="70%" style="display: block; margin: auto;" />
---
# 12.2 进阶——细节调整(目标图片1)
## 画出总体均值
.panelset[
.panel[.panel-name[code]
```r
s1 <- df.match.sum %>%
ggplot2::ggplot(.,
aes(x = Identity,
y = grand_mean_RT,
group = Valence,
color = Valence)) +
ggplot2::geom_line(position = position_dodge(0.5)) +
ggplot2::geom_point(size = 3,
position = position_dodge(0.5)) +
ggplot2::geom_errorbar(aes(ymin=grand_mean_RT-SE_RT,
ymax=grand_mean_RT+SE_RT),
width=.1,
position = position_dodge(0.5)) +
ggplot2::scale_y_continuous(limits = c(0.4, 0.9)) + #选取能纳入全部散点的范围
papaja::theme_apa()
```
.panel[.panel-name[figure]
<img src="chapter_12_files/figure-html/unnamed-chunk-26-1.png" width="80%" style="display: block; margin: auto;" />
]]]
---
# 12.2 进阶——细节调整(目标图片1)
## 加入个体数据
.panelset[
.panel[.panel-name[直接加入——拥挤]
```r
s2 <- s1 +
ggplot2::geom_point(data = df.match.subj,
aes(x = Identity,
y = RT_mean,
group = Valence))
```
<img src="chapter_12_files/figure-html/unnamed-chunk-28-1.png" width="70%" style="display: block; margin: auto;" />
.panel[.panel-name[加入抖动——混乱]
```r
s3 <- s1 +
ggplot2::geom_point(data = df.match.subj,
aes(x = Identity, y = RT_mean, group = Valence),
position = position_jitter(width = 0.1),
alpha = 0.5)
```
<img src="chapter_12_files/figure-html/unnamed-chunk-30-1.png" width="70%" style="display: block; margin: auto;" />
]]]
---
# 12.2 进阶——细节调整(目标图片1)
## 加入个体数据——如何得到规则的抖动?
.panelset[
.panel[.panel-name[将不同条件点的位置作为新变量]
```r
df.match.plot <- df.match.subj %>%
dplyr::mutate(conds = case_when(Identity == "Self" & Valence == "moral" ~ "0.88",
Identity == "Self" & Valence == "immoral" ~ "1.12",
Identity == "Other" & Valence == "moral" ~ "1.88",
Identity == "Other" & Valence == "immoral" ~ "2.12"),
conds = as.numeric(conds))
```
.panel[.panel-name[以conds为基础抖动]
```r
s4 <- s1 +
ggplot2::geom_point(data = df.match.plot,
aes(x = conds, y = RT_mean, group = Valence),
position = position_jitter(width = 0.08),
alpha = 0.5)
```
<img src="chapter_12_files/figure-html/unnamed-chunk-33-1.png" width="70%" style="display: block; margin: auto;" />
]]]
---
# 12.2 进阶——细节调整(目标图片1)
## 显示个体趋势
```r
s5 <- s4 +
ggplot2::geom_line(data = df.match.plot,
aes(x = conds, y = RT_mean, group = Sub),
linetype = 1,
size=0.8,
color="#000000",
alpha=0.1)
```
<img src="chapter_12_files/figure-html/unnamed-chunk-35-1.png" width="70%" style="display: block; margin: auto;" />
---
# 12.2 进阶——细节调整(目标图片1)
## 显示个体趋势——如何使点和线正确连接?
.panelset[
.panel[.panel-name[code]
```r
s6 <- s1 +
ggplot2::geom_point(data = df.match.plot,
aes(x = conds,
y = RT_mean,
group = as.factor(Sub)),
position = position_dodge(0.08),
color="#000000",
alpha = 0.05) +
ggplot2::geom_line(data = df.match.plot,
aes(x = conds,
y = RT_mean,
group = as.factor(Sub)),
position = position_dodge(0.08),
linetype = 1,
size=0.8,
color="#000000",
alpha=0.05) +
ggplot2::labs(y = "RT")
```
.panel[.panel-name[figure]
<img src="chapter_12_files/figure-html/unnamed-chunk-37-1.png" width="80%" style="display: block; margin: auto;" />
]]]
---
# 12.2 进阶——细节调整(目标图片1)
## 同理可得ACC的图
<br>
<br>
<img src="chapter_12_files/figure-html/unnamed-chunk-38-1.png" width="80%" style="display: block; margin: auto;" />
---
# 12.2 进阶——细节调整(目标图片1)
## 合并图片
```r
s9 <- s6 + s8 + plot_layout(guides = "collect")
s9
```
<img src="chapter_12_files/figure-html/unnamed-chunk-39-1.png" width="100%" />
---
# 12.2 进阶——细节调整(目标图片1)
## 保存图片
```r
# 保存为pdf更加清晰
ggplot2::ggsave(filename = "./picture/chp12/p1.pdf",
plot = s9,
width = 5,
height = 4)
```
---
# 12.2 进阶——细节调整
## 问题2:可视化层级模型的random effect
## 目标图片2
<img src="picture/chp12/target2.png" width="80%" style="display: block; margin: auto;" />
---
# 12.2 进阶——细节调整(目标图片2)
## 模型拟合
.panelset[
.panel[.panel-name[使用一个简单的模型]
```r
#此处选择12个被试是为了在展示的时候更清晰
sublist <- unique(df.match.trial$Sub)
target2 <- df.match.trial %>%
dplyr::filter(Sub == sublist[1:12]) %>%
dplyr::mutate(Label = factor(Label, levels = c("moralSelf", "moralOther", "immoralSelf", "immoralOther")),
Sub = factor(Sub))
model <- lme4::lmer(data = target2,
RT ~ Identity * Valence + (1 |Sub))
```
]]
---
# 12.2 进阶——细节调整(目标图片2)
## 随机效应森林图
.panelset[
.panel[.panel-name[data preprocessing]
```r
# 提取随机效应
ranef_df <- as.data.frame(ranef(model)$Sub) %>%
dplyr::mutate(Sub = row.names(.)) %>%
dplyr::rename(Intercept = "(Intercept)") %>%
dplyr::mutate(se = sqrt(diag(vcov(model))[1]),
lower = Intercept - 1.96 *se,
upper = Intercept + 1.96 *se) %>%
dplyr::arrange(Intercept) %>%
dplyr::mutate(Sub = factor(Sub, levels = .$Sub))
```
.panel[.panel-name[forest]
```r
# 绘制森林图
ranef_df %>%
ggplot2::ggplot(., aes(x=Intercept, y=Sub)) +
ggplot2::geom_point(size = 2) +
ggplot2::geom_errorbarh(aes(xmax = upper, xmin = lower),
height = .2, color = 'grey') +
ggplot2::geom_vline(xintercept = 0, linetype = 2) +
# ggplot2::facet_wrap(~ variable, nrow = 1) + # 按照对象分面
papaja::theme_apa()
```
<img src="chapter_12_files/figure-html/unnamed-chunk-44-1.png" width="65%" />
]]]
---
# 12.2 进阶——细节调整
## 问题3:使用雨云图(Raincloud plot)呈现数据的分布
## 雨云图将不在PPT中出现,感兴趣的同学可以自行回到rmd文件运行chunk
## 目标图片3
<img src="picture/chp12/target3.png" width="80%" style="display: block; margin: auto;" />
---
class: center, middle
<span style="font-size: 60px;">12.3 高级图片处理——magick</span> <br>
---
# 12.3 高级图片处理——magick
.pull-left[
.size6[
<br>
<br>
<br>
ggplot生成的图像有时需要进一步手动修改(如修改图片格式、图片拼接等),也可能需要批量修改。
R仍然可以处理。
magick包可以应用于所有常见图片操作(甚至包括PDF),具体功能可以参考相关文档 `\(^*\)`,在这里我们仅以图片剪裁与拼接为例。
]]
.pull-right[
<br>
<br>
<br>
<img src="picture/chp12/r.jpg" width="80%" />
]
.footnote[
----------------
.footfont[
注:[https://search.r-project.org/CRAN/refmans/magick/html/magick.html](https://search.r-project.org/CRAN/refmans/magick/html/magick.html)
]]
---
# 12.3 高级图片处理——magick
## 图片剪裁与拼接
.panelset[
.panel[.panel-name[查看图片]
假设我们希望这两张图变为横向排版,那么首先需要对图片进行剪裁,然后进行横向拼接。
<img src="picture/chp6/pr1.png" width="40%" />
.panel[.panel-name[读取图片]
```r
## 读取图片;图片可以是本地,也可以是图片的网址链接
img = magick::image_read('picture/chp6/pr1.png')
## 查看图片相关信息
img %>% magick::image_info()
```
```
## # A tibble: 1 × 7
## format width height colorspace matte filesize density
## <chr> <int> <int> <chr> <lgl> <int> <chr>
## 1 PNG 870 977 sRGB FALSE 92033 72x72
```
.panel[.panel-name[图片剪裁--语法]
.pull-left[
下面需要根据图片的width 和 height ,使用`magick::image_crop()`进行裁剪,geometry参数接受一个字符串,来对剪裁区域进行定位,比如`"850x480+10+10"`。
这个字符串包含两个部分:
- 第一部分:包含图片剪裁的长和宽(单位可以是百分比,但下面会使用像素),即`"850x480"`(注意:其中连接符为小写字母x),大概指右图中红色线条;
- 第二部分:包含起始点位置,即`"+10+10"`,意思是从左上角顶点向右10个像素,向下10个像素,大概对应右图中灰色点的位置,如果不写默认使用`+0+0`(即左上角顶点)。
]
.pull-right[
<img src="picture/chp12/crop_gram.jpg" width="100%" />
]
.panel[.panel-name[图片剪裁--结果]
```r
img %>% magick::image_crop('850x480+10+10')
```
<img src="chapter_12_files/figure-html/unnamed-chunk-51-1.png" width="80%" />
.panel[.panel-name[图片剪裁与合并]
```r
img1 = img %>% magick::image_crop('870x488')
img2 = img %>% magick::image_crop('870x488+0+485')
## 使用image_append进行拼接,令stack = F进行横向拼接(T为竖向)
*img3 = image_append(c(img1,img2),stack = F)
img3 %>% print()
```
```
## # A tibble: 1 × 7
## format width height colorspace matte filesize density
## <chr> <int> <int> <chr> <lgl> <int> <chr>
## 1 PNG 1740 488 sRGB FALSE 0 72x72
```
<img src="chapter_12_files/figure-html/unnamed-chunk-52-1.png" width="80%" />
.panel[.panel-name[其他]
```r
#### NOT RUN ####
# 保存图片到本地
image_write(image = img3,path = 'your path')
# 修改尺寸(可以以像素为单位,这里以百分比为例)
image_scale(img1,'40%')
# 旋转
image_rotate(img1,90)
# OCR(这里以英文为例,中文的识别率经测验确实不太行😢)
image_read("http://jeroen.github.io/images/testocr.png") %>%
image_ocr() %>%
cat()
```
]]]]]]]
---
# 网络资源
- ggplot2常用参数与函数汇总:https://zhuanlan.zhihu.com/p/637483028
- ggplot2位置调整参数:https://zhuanlan.zhihu.com/p/409489632
- ggplot2主题总结:https://zhuanlan.zhihu.com/p/463041897
- ggplot2分面总结:https://zhuanlan.zhihu.com/p/225852640
- patchwork常用功能:https://zhuanlan.zhihu.com/p/384456335
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightLines": true,
"highlightStyle": "github",
"countIncrementalSlides": false,
"seal": true,
"ratio": "16:9"
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
// add `data-at-shortcutkeys` attribute to <body> to resolve conflicts with JAWS
// screen reader (see PR #262)
(function(d) {
let res = {};
d.querySelectorAll('.remark-help-content table tr').forEach(tr => {
const t = tr.querySelector('td:nth-child(2)').innerText;
tr.querySelectorAll('td:first-child .key').forEach(key => {
const k = key.innerText;
if (/^[a-z]$/.test(k)) res[k] = t; // must be a single letter (key)
});
});
d.body.setAttribute('data-at-shortcutkeys', JSON.stringify(res));
})(document);
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>