-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchap8_axes.Rmd
1266 lines (842 loc) · 25.8 KB
/
chap8_axes.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
---
title: "chap8_axes"
author: "J.H AHN"
date: '2022 1 10 '
output:
html_document:
toc: TRUE
---
```{r setup, include=FALSE}
library(gcookbook)
library(tidyverse)
library(patchwork)
library(MASS)
knitr::opts_chunk$set(echo = TRUE)
```
<br>
### 8.1 Swapping X- and Y-Axes
<br>
<br>
```{r fig_8_1}
fig_8011 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot()
fig_8012 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
coord_flip()
fig_8011 + fig_8012
```
<br>
때로 축을 바꾸면 아이템의 순서를 거꾸로 배치하여야 할 때가 있다.
만약 x변수가 factor라면 `scale_x_discrete(limits=rev(levels(...)))`를 사용하여 순서를 바꿀 수 있다.
<br>
```{r fig_8_2}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
coord_flip() +
scale_x_discrete(limits=rev(levels(PlantGrowth$group)))
```
<br>
<br>
### 8.2 Setting the range of a continuous axis
<br>
<br>
**xlim**과 **ylim**을 사용하여 연속형 변수가 사용되는 축의 최대, 최솟값을 지정할 수 있다.
<br>
```{r fig_8_3}
fig_8031 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot()
fig_8032 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
ylim(0, max(PlantGrowth$weight))
fig_8031 + fig_8032
```
<br>
`ylim()`은 `scale_y_continuous()`을 이용하여 limit을 설정하는 것이다. (x도 마찬가지)
`scale_y_continuous()`을 이용하면 scale만 바꾸는 것으로 데이터가 살아있지만,
`coord_cartesian()`를 사용하면 범위 밖의 데이터는 지워진다.
<br>
```{r fig_8_4}
fig_8041 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_y_continuous(limits = c(5, 6.5))
fig_8042 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
coord_cartesian(ylim = c(5, 6.5))
fig_8041 + fig_8042
```
<br>
범위를 확장하고 싶을 때는 `expande_limits()`를 사용한다.
**하지만 범위를 줄일 수는 없다.**
<br>
```{r fig_8_5}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
expand_limits(y = 0)
```
<br>
<br>
### 8.3 Reversing a continuous axis
<br>
<br>
`scale_y_reverse()` 혹은 `scale_x_reverse()`를 사용하면 축방향을 반대로 돌릴 수 있다.
<br>
```{r fig_8_6}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_y_reverse()
```
<br>
`scale_y_reverse()`을 사용하지 않고 유사한 효과를 내려면 아래와 같이 최대, 최솟값의 순서를 바꾸면 된다.
<br>
```{r}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
ylim(6.5, 3.5)
```
<br>
`scale_y_continuous()`처럼 `scale_y_reverse()`는 `ylim()`과 함께 사용할 수 없다.
만약 축을 방향을 바꾸면서 range값을 세팅하고 싶다면 `scale_y_reverse()`안에서 limits을 설정해야 한다.
<br>
```{r fig_8_7}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_y_reverse(limits = c(8,0))
```
<br>
<br>
### 8.4 Changing the order of items on a categorical axis
<br>
<br>
범주형, 이산형 변수 축을 순서대로 정렬하기 위해서는 `scale_x_discrete()` 혹은 `scale_y_discrete()`안에 limits을 설정해야 한다.
순서는 매뉴얼로 정해줘야 하고 원하는 순서대로 벡터 형식으로 입력하면 된다.
원하는 변수만 보여주고 싶으면 limits에 원하는 변수만 선택한다.
<br>
```{r fig_8_8}
fig_8081 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(limits = c("trt1", "ctrl", "trt2"))
fig_8082 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(limits = c("ctrl", "trt1"))
fig_8081 + fig_8082
```
<br>
순서를 거꾸로 하고 싶으면 동일하게 `limits = rev(levels(...))`를 사용한다.
<br>
```{r fig_8_9}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(limits = rev(levels(PlantGrowth$group)))
```
<br>
<br>
### 8.5 Setting the scaling ratio of the X- and Y-axes
<br>
<br>
x축과 Y축의 비율을 정하기 위해서는 `coord_fixed()`를 사용한다.
<br>
<br>
```{r fig_8_10}
fig_8101 <-
marathon %>%
ggplot(aes(x = Half, y = Full)) +
geom_point() +
coord_fixed()
fig_8102 <-
marathon %>%
ggplot(aes(x = Half, y = Full)) +
geom_point() +
coord_fixed() +
scale_y_continuous(breaks = seq(0, 420, 30)) +
scale_x_continuous(breaks = seq(0, 420, 30))
fig_8101 + fig_8102
```
<br>
x, y축 사이의 비율을 1:1이 아닌 다른 특정한 비율을 넣고 싶다면 ratio 값을 설정한다.
<br>
<br>
```{r fig_8_11}
fig_8111 <-
marathon %>%
ggplot(aes(x = Half, y = Full)) +
geom_point() +
coord_fixed() +
scale_y_continuous(breaks = seq(0, 420, 30)) +
scale_x_continuous(breaks = seq(0, 420, 30))
fig_8112 <-
marathon %>%
ggplot(aes(x = Half, y = Full)) +
geom_point() +
coord_fixed(ratio = 1/2) +
scale_y_continuous(breaks = seq(0, 420, 30)) +
scale_x_continuous(breaks = seq(0, 420, 15))
fig_8111 + fig_8112
```
<br>
<br>
### 8.6 Setting the positions of tick marks
<br>
<br>
```{r fig_8_12}
fig_8121 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot()
fig_8122 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_y_continuous(breaks = c(4, 4.25, 4.5, 5, 6, 8))
fig_8121 + fig_8122
```
<br>
이산형 변수가 있는 축에서는 tick mark가 default이다.
limits에서 명시한 변수만 순서대로 그려진다.
이 상태에서 breaks를 설정하면 레벨을 바꿀 수 있는 반면 삭제하거나 순서를 바꿀 수는 없게된다.
<br>
```{r fig_8_13}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(limits = c("trt2", "ctrl"), breaks = "ctrl")
```
<br>
<br>
### 8.7 Removing tick marks and labels
<br>
<br>
tick labels을 삭제하고 싶을 경우에는 `theme(axis.text.y = element_blank())`를 사용하면 된다.
이 함수는 연속형 혹은 범주형 변수가 쓰이는 축에 모두 적용된다.
<br>
tick label은 독자적으로 조절되지만, tic marks와 grid line은 함께 조절되기 때문에 하나만 없앨 수는 없다.
<br>
```{r fig_8_14}
fig_8141 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
theme(axis.text.y = element_blank()) +
labs(subtitle = "no tick labels on y-axis")
fig_8142 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
theme(axis.text.y = element_blank(), axis.ticks = element_blank()) +
labs(subtitle = "no tick labels & marks on y-axis")
fig_8143 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_y_continuous(breaks = NULL) +
labs(subtitle = "with breaks = NULL")
fig_8141 + fig_8142 + fig_8143
```
<br>
<br>
### 8.8 Changing the text of tick labels
<br>
<br>
임의의 tick label을 사용하고 싶다면 breaks와 labels를 사용한다.
<br>
```{r fig_8_15}
fig_8151 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point()
fig_8152 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point() +
scale_y_continuous(breaks = c(50, 56, 60, 66, 72),
labels = c("Tiny", "Really\nshort", "Short", "Medium", "Tallish"))
fig_8151 + fig_8152
```
<br>
임의의 label을 모두 입력하기 보다는 하나의 포맷으로 정해두고 넣는 경우가 많다.
예를 들어 키를 피트(ft)와 인치(in)로 나타낼 때 5'6"와 같이 쓰는 경우다.
이런 작업을 하기위해서 먼저 포맷을 맞추는 함수를 만들어 입력된 값을 정해진 포맷으로 반환하게 해야 한다.
<br>
```{r}
footinch_formatter <- function(x) {
foot <- floor(x/12)
inch <- x %% 12
return(paste(foot, "'", inch, "\"", sep=""))
}
```
```{r}
footinch_formatter(56:64)
```
<br>
```{r fig_8_16}
fig_8161 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point() +
scale_y_continuous(labels = footinch_formatter)
fig_8162 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point() +
scale_y_continuous(breaks = seq(48, 72, 4),
labels = footinch_formatter)
fig_8161 + fig_8162
```
<br>
또 다른 포맷 변환으로 시간을 HH:MM:SS 형태로 바꾸는 것이 있다.
아래 함수는 분(minute)을 입력하면 시간:분:초의 형태로 변환해 준다.
<br>
```{r}
timeHMS_formatter <- function(x) {
h <- floor(x/60)
m <- floor(x %% 60)
s <- round(60 * (x %% 1))
lab <- sprintf("%02d:%02d:%02d", h, m, s)
lab <- gsub("^00:","", lab)
lab <- gsub("^0","",lab)
return(lab)
}
```
```{r}
timeHMS_formatter(c(0.33, 50, 51.25, 59.32, 60, 60.1, 130.23))
```
<br>
<br>
### 8.9 Changing the appearance of tick labels
<br>
<br>
```{r fig_8_17}
fig_8171 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(breaks = c("ctrl", "trt1", "trt2"),
labels = c("Control", "Treatment1", "Treatment2"))
fig_8172 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(breaks = c("ctrl", "trt1", "trt2"),
labels = c("Control", "Treatment1", "Treatment2")) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
fig_8173 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(breaks = c("ctrl", "trt1", "trt2"),
labels = c("Control", "Treatment1", "Treatment2")) +
theme(axis.text.x = element_text(angle = 30, hjust = 1, vjust = 1))
fig_8171 + fig_8172 + fig_8173
```
<br>
글자를 회전시키는 것외에도 size, style(bold/italic/normal), font family(Times, Helvetica) 등을 `element_text()`를 이용하여 변경할 수 있다.
size를 정할 때 쓴 `rel()`은 theme에서 쓰이는 argument로 다른 글자 대비 상대적인 크기를 얼마로 할지 결정하게 해 준다.
<br>
```{r fig_8_18}
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
scale_x_discrete(breaks = c("ctrl", "trt1", "trt2"),
labels = c("Control", "Treatment1", "Treatment2")) +
theme(axis.text.x = element_text(family = "Times", face = "italic",
color = "#8B0000", size = rel(0.9)))
```
<br>
<br>
### 8.10 Changing the text of axis labels
<br>
<br>
축의 text label을 변경하기 위해서는 `xlab()`, `ylab()`을 이용한다.
<br>
```{r fig_8_19}
fig_8191 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
xlab("Age in years") + ylab("Height in inches")
fig_8192 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
labs(x = "Age in years", y = "Height in inches")
fig_8191 + fig_8192
```
<br>
다른 방법으로는 `scale_*_continuous()`에 name으로 설정하는 방법이 있다.
<br>
```{r}
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
scale_x_continuous(name = "Age in years")
```
<br>
```{r fig_8_20}
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
scale_x_continuous(name = "Age \n(in years)")
```
<br>
<br>
### 8.11 Removing axis labels
<br>
<br>
축의 label을 지우고 싶으면 `theme(axis.title.x = element_blank())`를 사용한다.
<br>
```{r fig_8_21}
fig_8201 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot()
fig_8202 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
theme(axis.text.x = element_blank())
fig_8201 + fig_8202
```
<br>
label을 지우는 다른 방법으로는 빈 값을 넣는 방법이 있다.
하지만 이렇게 label을 지우면 원래 글자가 있던 자리의 공간이 글자가 있을 때와 동일하게 유지한다.
책에는 xlab을 쓸 때와 element_blank()를 쓸 때가 다르다고 되어 있는데 현재 ggplot2에는 같게 나옴.
<br>
```{r fig_8_21a}
fig_8211 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
theme(axis.title.x = element_blank()) +
labs(subtitle = "using element_blank()")
fig_8212 <-
PlantGrowth %>%
ggplot(aes(x = group, y = weight)) +
geom_boxplot() +
xlab("") +
labs(subtitle = "using xlab with empty value")
fig_8211 + fig_8212
```
<br>
<br>
### 8.12 Chnaging the apperance of axis labels
<br>
<br>
축의 label 외형을 바꾸고 싶으면 `axis.title.x()`를 사용
<br>
```{r fig_8_22}
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
theme(axis.title.x = element_text(face = "italic", color = "#8B0000", size = 14))
```
<br>
```{r fig_8_23}
fig_8231 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
ylab("Height\n(inches)") +
theme(axis.title.y = element_text(angle = 0, face = "italic", size = 14))
fig_8232 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
ylab("Height\n(inches)") +
theme(axis.title.y = element_text(angle = 90, face = "italic", size = 14))
fig_8231 + fig_8232
```
<br>
<br>
### 8.13 Showing lines along the axes
<br>
<br>
```{r fig_8_24}
fig_8241 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
theme(axis.line = element_line(color = "#000000"))
fig_8242 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
theme_bw() +
theme(panel.border = element_blank(),
axis.line = element_line(color = "#000000"))
fig_8241 + fig_8242
```
<br>
```{r fig_8_25}
fig_8251 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
theme_bw() +
theme(panel.border = element_blank(),
axis.line = element_line(color = "#000000", size = 4)) +
labs(subtitle = "with thick lines, only half overlaps")
fig_8252 <-
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, color = sex)) +
geom_point() +
theme_bw() +
theme(panel.border = element_blank(),
axis.line = element_line(color = "#000000", size = 4, lineend = "square")) +
labs(subtitle = "full overlap")
fig_8251 + fig_8252
```
<br>
<br>
### 8.14 Using a logarithmic axis
<br>
<br>
```{r}
Animals
```
```{r fig_8_26}
fig_8261 <-
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
labs(subtitle = "linear-scaled axes")
fig_8262 <-
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
scale_x_log10() + scale_y_log10() +
labs(subtitle = "logarithmic axes")
fig_8261 + fig_8262
```
<br>
```{r fig_8_27}
fig_8271 <-
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
scale_x_log10(breaks = 10^(-1:5)) +
scale_y_log10(breaks = 10^(0:3)) +
labs(subtitle = "manually specified breaks")
fig_8272 <-
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
scale_x_log10(breaks = 10^(-1:5),
labels = scales::trans_format("log10", scales::math_format(10^.x))) +
scale_y_log10(breaks = 10^(0:3),
labels = scales::trans_format("log10", scales::math_format(10^.x))) +
labs(subtitle = "with exponents for the tick labels")
fig_8271 + fig_8272
```
<br>
log변환을 하는 다른 방법은 데이터를 로그변환 시키는 방법이 있다.
<br>
```{r fig_8_28}
Animals %>%
ggplot(aes(x = log10(body), y = log10(brain), label = rownames(Animals))) +
geom_text(size = 3)
```
<br>
자연로그를 사용하기 위해서는 `scale`package가 필요하다.
<br>
```{r fig_8_29}
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
scale_x_continuous(trans = scales::log_trans(),
breaks = scales::trans_breaks("log", function(x) exp(x)),
labels = scales::trans_format("log", scales::math_format(e^.x))) +
scale_y_continuous(trans = scales::log2_trans(),
breaks = scales::trans_breaks("log2", function(x) 2^x),
labels = scales::trans_format("log2", scales::math_format(2^.x))) +
labs(subtitle = "different bases are used for the x and y axes")
```
<br>
한 축에만 로그를 쓰는 것도 가능한데 이건 금융관련 데이터를 보여줄 때 유용하다.
<br>
```{r}
aapl
```
<br>
```{r fig_8_30}
fig_8301 <-
aapl %>%
ggplot(aes(x = date, y = adj_price)) +
geom_line() +
labs(subtitle = "linear")
fig_8302 <-
aapl %>%
ggplot(aes(x = date, y = adj_price)) +
geom_line() +
scale_y_log10(breaks = c(2, 10, 50, 250)) +
labs(subtitle = "logarithmic")
fig_8301 / fig_8302
```
<br>
<br>
### 8.15 Adding ticks for a logarithmic axis
<br>
<br>
로그가 씌어진 축에 tick mark를 주기 위해서는 `annotate_logticks()`를 사용한다.
`annotate_logticks()`는 plot area 내부에 그려지는데 긴 tick mark는 10제곱을 나타내며, 짧은 tick mark는 5제곱을 나타낸다.
<br>
```{r fig_8_31}
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
annotation_logticks() +
scale_x_continuous(trans = scales::log_trans(),
breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x))) +
scale_y_continuous(trans = scales::log2_trans(),
breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x))) +
labs(subtitle = "log axes with diminishing tick marks")
```
<br>
내용을 보기 쉽게 하기 위해 `theme_bw()`를 사용하고 주눈금 사이에 보조눈금을 나타낸다.
보조눈금은 로그 스케일의 5를 가리키는 tick mark와 같은 의미가 아니라 주눈금의 절반 지점에 위치한다.
보조눈금을 그릴려면 `scales` package의 `minor_breaks()`를 직접 설정해야 한다.
`minor_breaks()`는 log10(5 * 10^(minpow:maxpow)를 log10(5) + minpow:maxpow 형식으로 줄여서 나타낸다.
<br>
```{r fig_8_32}
Animals %>%
ggplot(aes(x = body, y = brain, label = rownames(Animals))) +
geom_text(size = 3) +
annotation_logticks() +
scale_x_log10(breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x)),
minor_breaks = log10(5) + -2:5) +
scale_y_log10(breaks = scales::trans_breaks("log10", function(x) 10^x),
labels = scales::trans_format("log10", scales::math_format(10^.x)),
minor_breaks = log10(5) + -1:3) +
labs(subtitle = "log axes with ticks at each 5, and fixed coordinate ratio") +
coord_fixed() +
theme_bw()
```
<br>
<br>
### 8.16 Making a circular graph
<br>
<br>
`coord_polar()`를 사용하면 원그래프를 그릴 수 있다.
예제로 사용할 `wind` 데이터는 하루동안 5분간격으로 풍향(DirCat)과 풍속(SpeedCat)을 측정한 것이다.
풍향은 15도 간격으로 범주화가 되어있고, 풍속은 5m/s 단위로 범주화가 되어 있다.
<br>
```{r}
wind
```
<br>
polar plot을 그릴 때는 데이터를 왜곡하여 이해할 수 있는 위험에 주의해야 한다.
예를 들어 210도 풍향 부근에는 15개의 15-20m/s의 풍속 관측값이 있고, 13개의 >20m/s 풍속 관측값이 있다.
그런데 그냥 봐서는 >20m/s 관측치가 더 많은 것처럼 보이고(정말?? 난 그렇게 안 보이는데... 책에선 그렇다함) 10-15m/s 풍속은 식별하기가 어렵다.
<br>
```{r fig_8_33}
wind %>%
ggplot(aes(x = DirCat, fill = SpeedCat)) +
geom_histogram(binwidth = 15, boundary = -7.5) +
coord_polar() +
scale_x_continuous(limits = c(0,360))
```
<br>
식별하기 쉽게 범례를 거꾸로 배열하고 다른 팔레트를 사용하고, 아웃라인을 추가한다.
구분자는 익숙한 숫자로 바꾼다.