-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathggplot2_learn.Rmd
906 lines (687 loc) · 31.3 KB
/
ggplot2_learn.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
---
title: "ggplot2学习"
author:
- "[email protected]" #作者信息
- "`r Sys.Date()`" #自动获取当前日期
output:
prettydoc::html_pretty:
#可以从齿轮-Output Options中设置
css: sspai.css #css模板,定义整个文档的格式,比如一级标题的字体字号等
highlight: tango #代码高亮风格
# number_sections: yes #是否自动按节编号
# theme: cayman # 2
# theme: tactile #2
# theme: architect #3
theme: leonids #4
# theme: hpstr #5
toc: yes #是否自动生成目录
---
https://zhuanlan.zhihu.com/p/269616624
https://zhuanlan.zhihu.com/p/391832351
# 0.数据机构
[官网:https://ggplot2.tidyverse.org/](https://ggplot2.tidyverse.org/)
[全图](https://raw.githubusercontent.com/rstudio/cheatsheets/master/pngs/thumbnails/data-visualization-cheatsheet-thumbs.png)
# 1. base_R绘图
# 2. ggplot2绘图
[官网](https://ggplot2.tidyverse.org/reference/)
## 2.1 简介
### 2.1.1 ggplot2之父简
* ggplot2的作者为Hadley Wickham博士,一位为统计应用领域做出了突出贡献的统计学家,被号称为改变了R的男人;
### 2.1.2 ggplot2绘图步骤
ggplot2是基于图层图形语法(the Grammar of Graphics),可简单粗暴的理解为,您可以先绘制好图形的每一部分,然后将各部分相加形成一张完善的图形,使用ggplot2时,会反复使用如下几个对象,简单介绍:
一般步骤:
1. 准备数据,一般为数据框, 且一般为长表, 即每个观测时间占一行, 每个观测变量占一列。
2. 将数据输入到`ggplot()`函数中, 并指定参与作图的每个变量分别映射到哪些图形特性, 比如映射为x坐标、y坐标、颜色、形状等。 这些映射称为`aesthetic mappings`或`aesthetics`。
3. 选择一个合适的图形类型, 函数名以geom_开头, 如`geom_point()`表示散点图。 图形类型简称为geom。 将ggplot()部分与geom_xxx()部分用加号连接。 到此已经可以作图,下面的步骤是进一步的细化设定。
4. 设定适当的坐标系统, 如`coord_cartesian()`, `scale_x_log10()`等。 仍用加号连接。
5. 设定标题和图例位置等,如labs()。 仍用加号连接。
```{r}
# p <- ggplot(data=<输入数据框>, mapping=aes(<维度>=<变量名>, <维度>=<变量名>, <...>))
# p + geom_<图形类型>(<...>) +
# scale_<映射>_<类型>(<...>) +
# coord_<类型>(<...>) +
# labs(<...>)
```
其中<...>表示额外的选项。 变量p包含做出的图形的所有数据与设定, 变量名可以任意取。
### 2.1.3 数据集
```{r}
# devtools::install_github("kjhealy/socviz")
# install.packages('gapminder')
library('gapminder')
library(socviz)
```
1. `gapminder`扩展包的`gapminder`数据集, 有若干个国家不同年份的一些数据, 包括所属洲、期望寿命、人口数、人均GDP。 有1704个观测和6个变量。
2. socviz包的`gss_sm`数据集,是2016年美国一般社会调查数据的部分内容。 有2867个观测,32个变量。 社会调查数据的变量主要取属性值, 比如无序分类、有序分类、分组的数值、整数值等。
3. socviz包的`organdata`数据集, 是17个OECD国家历年的器官捐献情况以及一些其它记录。
4. socviz扩展包的`elections_historic`数据集。 包括美国历次总统大选当选人、所属党派、支持比例等。
5. socviz扩展包的`asasec`数据集。 这是美国社会学学会(ASA)的各分会2005年到2015年的一些数据。
6. ggplot2包中的`midwest`数据集包含了美国中西部的一些县的统计数据, 如面积等。
7. ggplot2包的`钻石`数据集。
## 2.2 作图的一般原则
1. 坏的图形可能有如下缺点:
*. 坏的品味。统计图形应该用尽可能少的图形元素表示尽可能多的数据, 从打印图形而言,即数据量与所用墨水比例越大越好。 没有必要的颜色、三维形态经常会影响读者对图形的认读。 这是Edward R. Tufte的观点, 但是过于极端也不好。
* 坏的数据。 即使图形本身的做法没有问题, 选择了错误的或者不合适的数据也会误导读者, 甚至于用错误数据做的很专业的图形会比粗陋的图形更能误导读者。
* 坏的感知。 不好的颜色选择、三维形状、坐标轴范围、宽高比都有可能对读者的认知有影响。
2. 作图时应考虑的一些因素:
* 数值型变量的不同值可以表示为:
* 同一坐标轴上的不同位置、
* 不同轴上的位置、
* 三维空间中的不同位置、
* 不同长度、
* 不同角度或者斜率、
* 不同面积、
* 颜色的不同明暗度、
* 不同颜色饱和度、
* 曲线的不同曲率、
* 三维体积,
> 这些表示的选择项越往后越难以被读者正确辨识。 使用颜色时,应该使用渐变的明暗度或者渐变色。
* 分类变量的不同值可以表示为:
* 不同分组、
* 不同颜色、
* 三维动态、
* 不同符号。
> 这些表示的选择项越往后越难辨识。 使用颜色时,应该使用明显不同的颜色而不应该使用渐变色。
对于最少是零的变量, 是否应该以零作为坐标轴的最低值需要考虑, 但没有一定的规则。 同一组数据在不同的坐标范围或者长宽比下曲线的斜率会有很大差别。
## 2.3 散点图:ggplot入门
* gapminder数据集有多个国家在多个年份的期望寿命与人均GDP值。绘制GDP对寿命的关系的散点图。
```{r}
library(ggplot2)
p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) # 完整写法:p <- ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp))
p + geom_point()
```
> 实际上,上面的程序等同于调用`print(p + geom_point())`。 在R函数中或者在循环中需要显式地调用`print()`, 否则不会显示结果。 当载入了tidyverse系统时可以写成 `(p + geom_point()) |> print()`。
### 2.3.1 增加拟合线`geom_smooth()`
* 用相同的映射做出散点图并叠加拟合曲线图
* `geom_smooth()`的默认设置调用了`gam()`函数来拟合曲线,
可以用geom_smooth()的参数选择不同的拟合方法, 如直线拟合`geom_smooth(method="lm")`:
```{r}
p <- ggplot(gapminder, aes(gdpPercap, lifeExp))
p + geom_point() +
geom_smooth() # geom_smooth() using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
p + geom_point() + geom_smooth(method="lm")
```
> 注意geom_xxx()函数计算所需的变量值是从ggplot()函数保存在变量p中的信息提取的。
### 2.3.2 修改坐标轴刻度`scale_x_log10()`
以上的所有图形中, x轴变量(人均GDP)分布非正态,严重右偏, 使得大多数散点重叠地分布在直角坐标系的左下角。 将x轴用对数刻度可以改善, 函数为scale_x_log10():
```{r}
p + geom_point() + geom_smooth(method="gam") + scale_x_log10()
```
> 广义可加模型拟合的曲线基本是一条直线。 注意, 对数刻度实际上是对原始数据进行对数变换, 而`geom_smooth()`的拟合计算是在对数变换之后进行的。
刚刚的图形的横坐标轴刻度不太友好, 可以调用`scales`扩展包的适当函数进行改善, 作为`scale_x_log10()`的`labels`选项:
```{r}
p + geom_point() +
geom_smooth(method="gam") +
scale_x_log10(labels=scales::dollar)
```
> `scale_xxx()`的labels选项指定如何标出坐标刻度数字, 参数值是一个函数对象, 如果`scales`包中找不到适当的功能, 可以自定义一个函数将数值转换为字符串。 `scales`包提供了`comma`, `date`, `dollar`, `math`, `number`, `ordinal`, `pvalue`, `scientific`, `time`等坐标刻度值转换函数。
### 2.3.3 颜色`color`、形状`shape`、线型`type`等映射
在`ggplot()`函数的`mapping`参数的`aes()`设定中将变量映射到x、y轴, 颜色、符号、线型等图形元素类型, 也可以作为图形设置将某些图形元素设置为固定值。
#### 2.3.3.1. 例1:用不同颜色表示不同大洲, 就是将`continent`变量映射到`color`:指定了将大洲映射到颜色维, 并不具体指定所用的颜色
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp,
color=continent))
p + geom_point() + geom_smooth(method = "loess") + scale_x_log10(label=scales::dollar)
```
> 1. `method = "loess"` : 带有局部多项式曲线拟合
> 2. 曲线使用了不同颜色但置信域颜色相同, 使得难以认读。 在图形右侧自动生成了颜色与continent变量值的对应关系图例。
#### 2.3.3.2. 例2:将`continent`变量映射到`fill`:将置信区间阴影的颜色也用不同大洲区分
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp,
color=continent))
p + geom_point() +
geom_smooth(aes(fill=continent), method = "loess") +
scale_x_log10(label=scales::dollar)
```
> 添加`fill`映射,自动添加图例
#### 2.3.3.3 尝试将颜色指定为一个固定值
我们发现, 散点并没有使用草绿色, 而且图形右侧有一个chartreuse4图例。 这是因为, **`aes()`仅用来指定变量与图形元素类型的映射**, 所以实际上是生成了一个仅有一个常数值"chartreuse4"的新变量, 用颜色表示这个新变量。为了指定固定颜色, 应将`color=`作为`geom_xxx()`函数的选项, 而不是放在`aes()`映射中, 如:
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp,
color = "chartreuse4"))
p + geom_point() +
geom_smooth(method="loess") +
scale_x_log10(labels=scales::dollar)
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp))
p + geom_point(color="chartreuse4") +
geom_smooth(method="loess") +
scale_x_log10(labels=scales::dollar)
```
### 2.3.4 修改`geom_xxx()`参数调整图像
* geom_xxx()函数接受许多关于颜色`colour`、透明度`alpha`、符号、线型`shape`的设置参数。 比如, 下面的程序指定了散点的透明度, 以及拟合直线的粗细:
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp))
p + geom_point(alpha=0.2, colour="red", shape=21, size=1) +
geom_smooth(method = "gam", color="cadetblue1", se = FALSE, linewidth = 4, alpha = 0.3) +
scale_x_log10(labels=scales::dollar)
```
> * size指定了线的以毫米为单位的粗细, Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
> * se = FALSE关闭了置信区间显示。
> * alpha =设置了透明度, 取0和1之间的值, 数值越小越透明。
> * 虽然这里设置了固定的透明度, 也可以在aes()中将透明度alpha映射到某个变量, 使得该变量值大小用点的透明度表示。
### 2.3.5 增加标题 `lab()`
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp))
p + geom_point(alpha = 0.3) +
geom_smooth(method="gam") +
scale_x_log10(labels=scales::dollar) +
labs(
x = "人均GDP",
y = "期望寿命(年数)",
title = "经济增长与期望寿命",
subtitle = "数据点为每个国家每年",
caption = "数据来源: gapminder" )
```
> 可以看出, labs()规定了上方的标题、小标题, x轴、y轴的标题, 右下方的标注(caption)。 坐标轴刻度数值的规定则需要在scale_xxx()函数中给出。
### 2.3.6 在`geom__`函数中映射变量
在前面的一个例图中, 在`ggplot()`函数中将`color`和`fill`映射到了`continent`变量, 使得不仅散点颜色代表了不同大洲, 还使得每个大洲单独拟合了曲线。 如果希望所有大洲拟合同一条曲线怎么办? </br>
在必要时, 可以在`geom_xxx()`函数中用`mapping = aes(<...>)`单独指定变量映射。 例如, 下面的程序在`geom_point()`中将不同大洲映射为不同颜色, 而不影响`geom_smooth()`中的颜色以及分组:
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp))
p + geom_point(mapping = aes(color = continent)) +
geom_smooth(method="loess") +
scale_x_log10(labels=scales::dollar)
```
* 也可以将一个分类变量映射到不同绘图符号。 例如,取gapminder 2007年数据子集, 将大洲映射到符号(`shape`):
```{r}
library(dplyr)
p <- ggplot(
data = filter(gapminder, year == 2007),
mapping = aes(
x = gdpPercap,
y = lifeExp,
shape = continent))
p + geom_point(alpha = 0.4, size = 4) +
scale_x_log10(labels=scales::dollar) # x轴刻度做对数转换
```
> 1. 映射仅适用于点数比较少的情况, 还用了size参数指定符号的大小(单位:毫米)
> 2. 绘图时参与映射的分类变量会自动产生分类效果, `color映射`与`fill映射`到分类变量时常常会起到与添加`group维`相同的作用, 但为了逻辑清晰起见, 需要分组时还应该显式地映射group维。
### 2.3.6 连续变量的颜色映射
也可以将连续变量映射为渐变色。 除了表示二元函数的等值线图以外这种方法并不利于读者认读。</br>
例如, 将人口数取自然对数映射为渐变色:
```{r}
p <- ggplot(gapminder, aes(
x = gdpPercap,
y = lifeExp,
color = log(pop)))
p + geom_point() +
geom_smooth(method="loess") +
scale_x_log10(labels=scales::dollar)
```
### 2.3.7 保存
在`ggsave()`中可以用`scale =`指定放大比例, 用`height =`指定高度, 用`width =`指定宽度,用`units =`指定高度和宽度的单位,单位可以是in, cm, mm。如:
```{r}
ggout01 <- p + geom_point()
ggsave(filename="文件名.pdf", plot=ggout01,
height=12, width=8, units="cm")
```
## 2.4 折线图、分组、切片
### 2.4.1 图形中的分组和折线图
考虑`gapminder`数据集中每个国家的期望寿命随时间(年)的变化
```{r 最初的图}
ggplot(gapminder, aes(year, lifeExp)) + geom_line()
```
> `geom_line()`会自动将x坐标从小到大排序, 然后再连接相邻的点
#### 2.4.1.1 `group`映射 - 分组
分组`(group)`与`x`、`y`、`color`、`fill`一样可以映射到一个变量, 但仅能映射到分类变量
```{r}
ggplot(gapminder, aes(year, lifeExp, group=country)) + geom_line()
```
> 结果图形中每一条曲线对应一个国家。 为了查探其中最下方的不稳定曲线是哪一个国家,使用筛选观测的功能:
#### 2.4.1.2 最不稳定的国家
```{r}
gapminder |> filter(lifeExp < 30, year >= 1990) # 国家是 Rwanda
```
* 每个点画出散点符号
```{r}
gapminder |>
filter(country == "Rwanda") |>
ggplot(aes(
x = year,
y = lifeExp)) +
geom_line() +
geom_point()
```
> 过管道运算符`|>`将筛选行子集得到的数据框作为第一自变量传送给了`ggplot()`函数, 然后就可以继续用+号添加进一步的作图命令。
* 用geom_area()作类似图形, 但在折线下方填充颜色:
```{r}
gapminder |>
filter(country == "Rwanda") |>
ggplot(aes(
x = year,
y = lifeExp))+
geom_area(fill="darkseagreen1", alpha=0.5)
```
> 这种图形的纵坐标应该从0开始, 使得阴影部分的大小与纵坐标值成比例, 这也是ggplot2的默认做法。
### 2.4.2 x坐标不是数值型变量而是因子或者字符型, 则两点之间不会相连
* `gapminder`的Rwanda子集中的year转换成因子,再画折线图:
```{r}
gapminder |>
filter(country == "Rwanda") |>
mutate(year = factor(
year, levels = seq(1952, 2007, by=5))) |>
ggplot(aes(
x = year,
y = lifeExp)) +
geom_line()
```
> 没有得到应有的结果。 这是因为因子year起到了分组作用, 相当于每个年份为一组, **连线只能在组内连**, 但每组仅有一个观测。 这时, 显式地指定group变量可以解决问题:
```{r}
gapminder |>
filter(country == "Rwanda") |>
mutate(year = factor(
year, levels = seq(1952, 2007, by=5))) |>
ggplot(aes(
x = year, y = lifeExp, group = country)) +
geom_line(color = 'green', linetype = 6, linewidth = 1, alpha=0.5)
```
可以在geom_line()函数中用color参数指定颜色, 用`linetype`参数指定线型, 用`linewidth`参数指定以毫米为单位的粗细。 线型包括:
* 0:不画线;
* 1:solid;实线;
* 2:dashed;破折号组成的虚线
* 3:dotted;点线
* 4:dotdash;点线与破折线间隔出现
* 5:longdash;长破折号组成的虚线
* 6:twodash。点长画线
## 2.5 切片(facet)
### 2.5.1 `facet_wrap`基础切片
前面所有国家的图包含了过多的曲线, 使得图形表现得很拥挤。 可以将一个作图区域拆分成若干个小块, 称为切片或者分面(facet), 按照某一个或两个分类变量的不同值将数据分为若干个子集, 每个数据子集分别在切片上作图。
* 每个大洲的图形分别放置在一个切片上, **切片不是一种变量映射, 而是一种图形摆放方法, 所以不设置在aes()函数内, 而是用facet_wrap()函数规定**
```{r}
ggplot(gapminder, aes(
x = year,
y = lifeExp,
group = country)) +
geom_line() +
facet_wrap(~ continent)
```
* 参数
* 参数`strip_position`和参数`switch`调整标签的上下左右。
* 参数`scales`设定各切片的xy轴的取值范围。
* 默认为"fixed", 即所有切片的x轴、y轴都范围一致,
* "free_x"则允许各切片的x轴不统一,
* "free_y"允许各切片的y轴不统一,
* "free"允许各切片的x轴和y轴都不统一。
* `ncol`参数指定切片的列数, 用`nrow`指定切片的行数。绘图顺序是从左向右。各个切片的次序应该设定为一定的合理次序, 比如用来分类的变量本身有序, 或者令各切片中的数据值有一定的增减次序。
* 下面的程序将曲线颜色变浅, 对每个大洲增加了拟合曲线, 增加了适当的标题和坐标轴标签。
```{r}
ggplot(gapminder, aes(
x = year,
y = lifeExp)) +
geom_line(
mapping = aes(group = country),
color = "gray70") +
geom_smooth(
method = "loess",
color="cyan",
se = FALSE,
size = 1.1) +
facet_wrap(~ continent, ncol = 2) +
labs(
x = "年份",
y = "期望寿命",
title = "五个大洲各国期望寿命变化趋势")
```
> 1. 这时不能使用统一的group = country映射, 否则拟合曲线就是对每个国家都单独有一条拟合曲线, 而不是每幅切片中仅有一条拟合曲线。 办法是仅在geom_line()中给出group = country的映射, 但在geom_smooth()中则不用group维。 注意group = country的设置从ggplot()函数中转移到了geom_line()函数中, 否则就意味着拟合线也需要按照国家分组, 而不是按大洲分组。
> `group = country`设置在`geom_line()`函数
### 2.5.2 `facet_grid()`两分类变量交叉分组分配切片
```{r}
p <- ggplot(gss_sm, aes(
x = age,
y = childs))
p + geom_point(alpha = 0.2)
```
> 有过多的重叠点。 将观测按照性别(sex)和种族(race)交叉分组, 分配到不同的切片上:
```{r}
p <- ggplot(gss_sm, aes(
x = age,
y = childs))
p + geom_point(alpha=0.2) +
geom_smooth() +
facet_grid(sex ~ race)
```
> 这里虽然没有映射group维, 但还是按性别和种族对数据集分成了6个子集, 每个切片中仅有一个自己的数据。
## 2.6 数据变换与条形图
有些`geom_xxx()`函数直接按照数据值作图, 如`geom_point()`、`geom_line()`, 而`geom_smooth()`这样的函数则会按照某种算法计算并对计算结果作图。 `geom_xxx()`都有默认的`stat_xxx()`函数用来计算, 也可以人为指定不同的统计规则。
### 2.6.1 `geom_bar()`自动统计频数并做条形图
使条形的高度与每个组中的观察值的数目成正比
* 对`gss_sm`数据集的`bigregion变量`作频数条形图:
```{r}
ggplot(gss_sm, aes(x=bigregion)) +
geom_bar()
```
> 结果是每个大区的受访者人数的条形图。 图形中x映射是用户指定的, 而y轴则是自动计算的频数。 实际上, geom_bar()自动调用了统计函数`stat_freq()`对每个大区计算频数, 生成新变量`count`和`prop`。 geom_bar()默认使用count(频数)。
### 2.6.2 `geom_col()` 数据中的值表示条形图的高度
虽然ggplot2可以做统计, 但最好还是预先统计好频数, 仅用ggplot2绘图
```{r}
df1 <- gss_sm |>
select(bigregion) |>
count(bigregion) |>
mutate(ratio = n /sum(n))
ggplot(df1, aes(x=bigregion, y=n)) +
geom_col()
# 纵坐标修改成比例
ggplot(df1, aes(
x = bigregion,
y = ratio)) +
geom_col() +
labs(y = "Ratio")
```
> x轴的分组较多时,区分各组的文字标签可能会重叠。 为此, 可以将文字标签旋转45度角;
> `coord_flip()`函数可以将x轴和y轴互换
```{r}
df1 <- gss_sm |>
select(bigregion)|>
count(bigregion)|>
mutate(ratio = n/sum(n))
ggplot(df1, aes(
x = bigregion,
y = ratio)) +
geom_col()+
labs(y = "Ratio") +
theme(
axis.text.x = element_text(
angle = 45, vjust = 1, hjust = 1)
)
# xy轴互换
ggplot(df1, aes(
x = bigregion,
y = ratio)) +
geom_col() +
labs(y = "Ratio") +
coord_flip()
```
* `theme(组件 = element_功能())`
* `hjust`和`vjust`仅在0和1之间限定, 0表示左对齐, 1表示右对齐.
### 2.6.3 丰富的色彩
下面的例子作`gss_sm`数据集中`religion`变量的频数条形图, 并给不同的条形自动分配不同的颜色, 方法是指定`fill = religion`
```{r}
df2 <- gss_sm |>
select(religion) |>
count(religion)
p <- ggplot(df2, aes(
x = religion,
y = n,
fill = religion))
p + geom_col() + labs(y = "Count")
```
> 将`religion`同时映射到`x`维与`fill`维,所以对应`fill`维在图形右侧出现了图例, 这是多余的。
* 调用`guides(fill = "none")`可以人为指定不做关于填充色的图例:
```{r}
df2 <- gss_sm |>
select(religion) |>
count(religion)
p <- ggplot(df2, aes(
x = religion,
y = n,
fill = religion))
p + geom_col() +
labs(y = "Count") +
guides(fill = "none")
```
> 从可视化理论的角度看, 上图中的不同颜色是多余的, 用同一颜色更能强调数据本身。
### 2.6.4 分段与并列条形图
上面的条形图展现了单个分类变量的频数分布。 两个分类变量的交叉频数分布可以用分段条形图或者并列条形图表现。</br>
```{r}
df3 <- gss_sm |>
select(bigregion, religion) |>
group_by(bigregion, religion) |>
summarise(n = n(), .groups="drop_last") |>
mutate(ratio = n / sum(n))
```
---
### theme()
https://zhuanlan.zhihu.com/p/463041897
### `guides()`图例布局函数
* `guide_legend()`函数: 离散型
* `guid_colorbar()`函数: 连续型
#######################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
### 2.2.1 几何对象(geom)
`geometric objects`,譬如散点`points`、 线性`lines`、柱状`bars`及方图`Histogram`等,可绘制的geom为:
>ggplot2::geom_ </br>
ggplot2::geom_abline </br>
ggplot2::geom_area </br>
ggplot2::geom_bar </br>
ggplot2::geom_bin2d </br>
ggplot2::geom_blank </br>
ggplot2::geom_boxplot </br>
ggplot2::geom_col 条形图, x轴为类别,y轴为每个类别对应的数值</br>
ggplot2::geom_contour </br>
ggplot2::geom_contour_filled </br>
ggplot2::geom_count </br>
ggplot2::geom_crossbar </br>
ggplot2::geom_curve </br>
ggplot2::geom_density </br>
ggplot2::geom_density_2d </br>
ggplot2::geom_density2d_filled </br>
ggplot2::geom_dotplot </br>
ggplot2::geom_errorbar </br>
ggplot2::geom_errorbarh </br>
ggplot2::geom_freqpoly </br>
ggplot2::geom_function </br>
ggplot2::geom_hex </br>
ggplot2::geom_histogram </br>
ggplot2::geom_hline </br>
ggplot2::geom_jitter </br>
ggplot2::geom_label </br>
ggplot2::geom_line </br>
ggplot2::geom_linerange </br>
ggplot2::geom_map </br>
ggplot2::geom_point </br>
ggplot2::geom_pointrange </br>
ggplot2::geom_polygon </br>
ggplot2::geom_qq </br>
ggplot2::geom_qq_line </br>
ggplot2::geom_quantile </br>
ggplot2::geom_raster </br>
ggplot2::geom_rect </br>
ggplot2::geom_ribbon </br>
ggplot2::geom_rug </br>
ggplot2::geom_segment </br>
ggplot2::geom_sf </br>
ggplot2::geom_sf_label </br>
ggplot2::geom_sf_text </br>
ggplot2::geom_smooth </br>
ggplot2::geom_spoke </br>
ggplot2::geom_step </br>
ggplot2::geom_text </br>
ggplot2::geom_tile </br>
ggplot2::geom_violin </br>
ggplot2::geom_vline </br>
ggplot2::get_element_tree </br>
### 2.2.2 标度(scale)
将数据取值映射到图形空间,使用颜色,形状,大小表示不同取值,使用图例,网格线展示标度),可使用的函数:
> ggplot2::scale_ </br>
ggplot2::scale_alpha_binned </br>
ggplot2::scale_alpha_date </br>
ggplot2::scale_alpha_datetime </br>
ggplot2::scale_color_brewer </br>
ggplot2::scale_color_date </br>
ggplot2::scale_color_datetime </br>
ggplot2::scale_color_discrete </br>
ggplot2::scale_color_fermenter </br>
ggplot2::scale_color_gradientn </br>
ggplot2::scale_color_identity </br>
ggplot2::scale_color_stepsn </br>
ggplot2::scale_colour_continuous </br>
ggplot2::scale_colour_datetime </br>
ggplot2::scale_colour_discrete </br>
ggplot2::scale_colour_identity </br>
ggplot2::scale_colour_ordinal </br>
ggplot2::scale_colour_stepsn </br>
ggplot2::scale_continuous_identity </br>
ggplot2::scale_discrete_manual </br>
ggplot2::scale_fill_date </br>
ggplot2::scale_fill_datetime </br>
ggplot2::scale_fill_fermenter </br>
ggplot2::scale_fill_grey </br>
ggplot2::scale_fill_manual </br>
ggplot2::scale_fill_steps </br>
ggplot2::scale_linetype_binned </br>
ggplot2::scale_linetype_discrete </br>
ggplot2::scale_shape </br>
ggplot2::scale_shape_ordinal </br>
ggplot2::scale_size_area </br>
ggplot2::scale_size_identity </br>
ggplot2::scale_size_manual </br>
ggplot2::scale_size_ordinal </br>
ggplot2::scale_type </br>
ggplot2::scale_x_datetime </br>
ggplot2::scale_x_sqrt </br>
ggplot2::scale_y_binned </br>
ggplot2::scale_y_discrete </br>
ggplot2::scale_y_sqrt </br>
ggplot2::scale_y_time </br>
### 2.2.3 坐标系(coord)
描述数据如何映射到图形,同时包含坐标轴和网格线axes, gridlines
>ggplot2::coord_ </br>
ggplot2::coord_cartesian </br>
ggplot2::coord_equal </br>
ggplot2::coord_fixed </br>
ggplot2::coord_flip </br>
ggplot2::coord_map </br>
ggplot2::coord_munch </br>
ggplot2::coord_polar </br>
ggplot2::coord_quickmap </br>
ggplot2::coord_sf </br>
ggplot2::coord_trans </br>
### 2.2.4 统计变换(stat)
对数据的汇总,可使用的函数:
> ggplot2::stat_ </br>
ggplot2::stage </br>
ggplot2::standardise_aes_names </br>
ggplot2::stat </br>
ggplot2::stat_bin </br>
ggplot2::stat_bin_2d </br>
ggplot2::stat_bin_hex </br>
ggplot2::stat_bin2d </br>
ggplot2::stat_binhex </br>
ggplot2::stat_boxplot </br>
ggplot2::stat_contour </br>
ggplot2::stat_contour_filled </br>
ggplot2::stat_count </br>
ggplot2::stat_density </br>
ggplot2::stat_density_2d </br>
ggplot2::stat_density_2d_filled </br>
ggplot2::stat_density2d </br>
ggplot2::stat_density2d_filled </br>
ggplot2::stat_ecdf </br>
ggplot2::stat_ellipse </br>
ggplot2::stat_function </br>
ggplot2::stat_identity </br>
ggplot2::stat_qq </br>
ggplot2::stat_qq_line </br>
ggplot2::stat_quantile </br>
ggplot2::stat_sf </br>
ggplot2::stat_sf_coordinates </br>
ggplot2::stat_smooth </br>
ggplot2::stat_spoke </br>
ggplot2::stat_sum </br>
ggplot2::stat_summary </br>
ggplot2::stat_summary_2d </br>
ggplot2::stat_summary_bin </br>
ggplot2::stat_summary_hex </br>
ggplot2::stat_summary2d </br>
ggplot2::stat_unique </br>
ggplot2::stat_ydensity </br>
### 2.2.5 分面(facet)
将数据拆分为小子集,对各子集作图并联合展示,也成条件作图或网格图),可使用的函数:
> ggplot2::facet_
ggplot2::facet_grid </br>
ggplot2::facet_wrap </br>
ggplot2::facet_null </br>
### 2.2.6 绘图主题(theme)
主题涉及图形更细的方面,如背景色,字体大小等
>ggplot2::theme_ </br>
ggplot2::theme_bw </br>
ggplot2::theme_classic </br>
ggplot2::theme_dark </br>
ggplot2::theme_get </br>
ggplot2::theme_gray </br>
ggplot2::theme_grey </br>
ggplot2::theme_light </br>
ggplot2::theme_linedraw </br>
ggplot2::theme_minimal </br>
ggplot2::theme_replace </br>
ggplot2::theme_set </br>
ggplot2::theme_test </br>
ggplot2::theme_update </br>
ggplot2::theme_void </br>
## 2.3 ggplot2快速绘图
### 2.3.1 ggplot2内置数据集
```{r}
library('ggplot2')
data(package = 'ggplot2')#查看ggplot2内置数据集
# Data sets in package ‘ggplot2’:
#
# diamonds Prices of over 50,000 round cut diamonds
# economics US economic time series
# economics_long US economic time series
# faithfuld 2d density estimate of Old Faithful data
# luv_colours 'colors()' in Luv space
# midwest Midwest demographics
# mpg Fuel economy data from 1999 to 2008 for 38 popular models
# of cars
# msleep An updated and expanded version of the mammals sleep
# dataset
# presidential Terms of 12 presidents from Eisenhower to Trump
# seals Vector field of seal movements
# txhousing Housing sales in TX
```
### 2.3.2 三要素(data, aes, geom)
* 数据集(data)
* 图像属性(aes), 即指定x、y轴要投影的数据
* 几何对象(geom), 此处为散点图
```{r}
library('ggplot2')
ggplot(data = mpg,
mapping = aes(x = displ, y=hwy)) +
geom_point()
```
#### 2.3.2.1 aes设置
* `colour`, `size`, `shape` 等等
* `colour`: 按变量class分类绘制不同类不同颜色的散点图
* `shape`: 按变量drv不同绘制不同类不同形状散点图
* `size`: 变量cyl值大小绘制不同类不同size散点图
```{r}
library('ggplot2')
ggplot(data = mpg,
mapping = aes(x = displ, y=hwy, colour=class)) +
geom_point()
ggplot(mpg, aes(displ, hwy, shape = drv)) +
geom_point()
ggplot(mpg, aes(displ, hwy, size = cyl)) +
geom_point()
```
#### 2.3.2.2 分面(facet)
```{r}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~class)
```
#### 2.3.2.3 几何对象(geom)
```{r}
library(gridExtra)
p1 <- ggplot(mpg, aes(drv, hwy)) + geom_jitter()
p2 <- ggplot(mpg, aes(drv, hwy)) + geom_boxplot()
p3 <- ggplot(mpg, aes(drv, hwy)) + geom_violin()
p4 <- ggplot(mpg, aes(hwy)) + geom_histogram()
p5 <- ggplot(mpg, aes(hwy)) + geom_freqpoly()
p6 <- ggplot(mpg, aes(manufacturer)) + geom_bar()
p7 <- ggplot(economics, aes(date, unemploy/pop)) + geom_line()#时间序列图
p8 <- ggplot(economics, aes(unemploy/pop, uempmed)) + geom_path() + geom_point()
grid.arrange(p1, p2, p3, p4, p5, p6, p7, p8, nrow = 4) #分行显示子图
```