-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchap13_miscellaneous_graphs.Rmd
1440 lines (933 loc) · 30.7 KB
/
chap13_miscellaneous_graphs.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: "chap13_miscellaneous_graphs"
author: "J.H AHN"
date: '2022 1 12 '
output:
html_document:
toc: TRUE
---
```{r setup, include=FALSE}
library(gcookbook)
library(tidyverse)
library(patchwork)
library(corrplot)
knitr::opts_chunk$set(echo = TRUE)
```
<br>
<br>
### 13.1 Making a correlation matrix
<br>
<br>
```{r}
mcor <- cor(mtcars)
# print mcor and round to 2 digits
round(mcor, digits = 2)
```
```{r fig_13_1}
corrplot(mcor)
```
<br>
tl = text label을 의미하는 것으로 tl.col = text label의 색깔, tl.srt = text label의 각도를 의미
shade.lwd = shade 부분의 선 두께, shade.col = shade 부분의 선 색깔을 의미
<br>
```{r}
corrplot(mcor, method = "shade", shade.col = NA, tl.col = "#000000", tl.srt = 45)
```
<br>
col = color를 몇 등분하여 나타낼 것인지를 넣는 것임.
addCoef.col = shade 내부에 Coefficient 값을 무슨 색으로 나타낼 것인지
addCoefasPercent = shade 내부에 Coefficient 값을 %로 나타낼 것인지
(책에서는 addcolorlabel = "no"로 되어 있는데 현재 버전에서는 사용되지 않는 argument임)
<br>
```{r fig_13_3}
# generate a lighter palette
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(mcor, method = "shade", shade.col = NA, tl.cor = "#000000", tl.srt = 45,
col = col(200), addCoef.col = "#000000", addCoefasPercent = TRUE, order = "AOE")
```
<br>
<br>
### 13.2 Plotting a function
<br>
<br>
적절한 x값 범위에서 dummy data frame을 이용하여 plot을 하기 위해서 `stat_function()`을 사용한다.
`dt()`는 student distribution을 나타내고 df는 자유도(degree of freedom), ncp는 non-centrality parameter를 의미한다.
<br>
```{r fig_13_4}
# the data frame is only used for setting the range
p <-
data.frame(x = c(-3,3)) %>%
ggplot(aes(x = x))
fig13041 <-
p + stat_function(fun = dnorm) +
labs(subtitle = "dnorm(x, mean = 0, sd = 1")
fig13042 <-
p + stat_function(fun = dt, args = list(df = 2)) +
labs(subtitle = "dt(x, df, ncp)")
fig13041 + fig13042
```
<br>
아래와 같이 user define function을 사용할 수도 있다.
그래프를 그릴 때 좀 더 smooth한 그래프를 그리고 싶다면 `stat_function()`에 n값을 크게 지정해주면 된다.
예를 들어 `stat_function(fun = myfun, n = 200)과 같이.
<br>
```{r fig_13_5}
myfun <- function(xvar) {
1/(1 + exp(-xvar + 10))
}
data.frame(x = c(0,20)) %>%
ggplot(aes(x = x)) +
stat_function(fun = myfun)
```
<br>
<br>
### 13.3 Shading a subregion under a function curve
<br>
<br>
<br>
Curve 아래 부분을 표시하고 싶다면 범위가 벗어나는 부분은 NA처리를 하고 Curve 주변을 감싸는 함수 생성이 필요함.
<br>
```{r fig_13_6}
# Return dnorm(x) for 0 < x <2, and NA for all other x
dnorm_limit <- function(x) {
y <- dnorm(x)
y[x < 0 | x > 2] <- NA
return(y)
}
# ggplot() with dummy data
p <-
data.frame(x = c(-3,3)) %>%
ggplot(aes(x = x))
p +
stat_function(fun = dnorm_limit, geom = "area", fill = "#0000FF", alpha = 0.2) +
stat_function(fun = dnorm)
```
```{r}
limitRange <- function(fun, min, max) {
function(x) {
y = fun(x)
y[x < min | x > max] <- NA
return(y)
}
}
# This returns a function
dlimit <- limitRange(dnorm, 0, 2)
# Now we'll try out the new function -- it only returns values for inputs
# between 0 and 2
dlimit
```
```{r}
p + stat_function(fun = dnorm) +
stat_function(fun = limitRange(dnorm, 0, 2),
geom = "area", fill = "#0000FF", alpha = 0.2)
```
<br>
### 13.4 Creating a network graph
<br>
<br>
`igraph` package를 사용하여 network graph를 그릴 수 있음.
```{r fig_13_7}
library(igraph)
# Set the plotting area into a 1(row) x 2(col) array
par(mfrow = c(1,2))
# Specify edges for a directed graph
gd <- graph(c(1,2,2,3,2,4,1,4,5,5,3,6))
fig_13071 <- plot(gd)
# For an undirected graph
gu <- graph(c(1,2,2,3,2,4,1,4,5,5,3,6), directed = FALSE)
# No labels
fig_13072 <- plot(gu, vertex.label = NA)
```
<br>
```{r}
str(gd)
```
<br>
```{r}
str(gu)
```
<br>
```{r}
madmen2
```
```{r fig_13_8}
# Create a graph object from the data set
g <-
madmen2 %>% graph.data.frame(directed = TRUE)
# Remove unnecessary margins
par(mar = c(0,0,0,0))
plot(g, layout = layout.fruchterman.reingold, vertex.size = 8,
edge.arrow.size = 0.5, vertex.label = NA)
```
<br>
```{r fig_13_9}
# Remove unnecessary margins
par(mar = c(0,0,0,0))
plot(g, layout = layout.circle, vertex.size = 8, vertex.label = NA)
```
<br>
### 13.5 Using text labels in a network graph
<br>
<br>
```{r fig_13_10}
# Copy data and drop every other row
m <- madmen[1:nrow(madmen) %% 2 == 1,]
g <- graph.data.frame(m, directed = FALSE)
# Print out the names of each vertex
V(g)$name
plot(g, layout = layout.fruchterman.reingold)
```
<br>
같은 효과를 내는 다른 방법은 `plot()`으로 argument를 보내는 대신에 `V()`를 사용하는 것이다.
<br>
```{r}
# This is equivalent to the preceding code
V(g)$size <- 4
V(g)$label <- V(g)$name
V(g)$label.cex <- 0.8
V(g)$label.dist <- 0.4
V(g)$label.color <- "#000000"
# Set a property of the entire graph
g$layout <- layout.fruchterman.reingold
plot(g)
```
<br>
`E()`를 사용하여 edge의 속성도 설정할 수 있다.
```{r fig_13_11}
# View the edges
E(g)
# Set some of the labels to "M"
E(g)[c(2,11,19)]$label <- "M"
# Set color of all the grey, and then color a few red
E(g)$color <- "gray70"
E(g)[c(2,11,19)]$color <- "#FF0000"
plot(g)
```
<br>
### 13.6 Creating a heat map
<br>
<br>
`geom_tile()` 혹은 `geom_raster()`를 사용하여 연속형 변수를 맵핑할 수 있다.
<br>
```{r}
presidents
```
```{r}
str(presidents)
```
<br>
`ggplot()`에 사용할 수 있는 형태로 변환한다.
숫자형 값을 가지는 열로 구성된 data.frame으로 변환
`time()`은 time series에서 time vector를 생성해주는 함수이고 `cycle()`은 각 관측값의 사이클의 위치를 반환하는 함수임.
<br>
```{r}
pres_rating <-
data.frame(
rating = as.numeric(presidents),
year = as.numeric(floor(time(presidents))),
quarter = as.numeric(cycle(presidents))
)
pres_rating
```
<br>
```{r fig_13_12}
# Base plot
fig_13121 <-
pres_rating %>%
ggplot(aes(x = year, y = quarter, fill = rating)) +
geom_tile() +
labs(subtitle = "geom_tile()")
# Using geom_raster() - looks the saem, but a little more efficient
fig_13122 <-
pres_rating %>%
ggplot(aes(x = year, y = quarter, fill = rating)) +
geom_raster() +
labs(subtitle = "geom_raster()")
fig_13121 + fig_13122
```
<br>
좀 더 이해하기 쉽게 표현하려면 y축 값을 거꾸로 나열하고 x축에 4년 주기로 tick marks를 준다.
<br>
```{r 13_13}
pres_rating %>%
ggplot(aes(x = year, y = quarter, fill = rating)) +
geom_raster() +
scale_x_continuous(breaks = seq(1940, 1976, 4)) +
scale_y_reverse() +
scale_fill_gradient2(midpoint = 50, mid = "gray70", limits = c(0,100))
```
<br>
### 13.7 Creating a three-dimensional scatter plot
<br>
3D graphic를 구현하기 위해 OpenGL graphic과 interface를 위한 `rgl` package가 필요
<br>
```{r fig_13_14}
library(rgl)
plot3d(mtcars$wt, mtcars$disp, mtcars$mpg, type = "s", size = 0.75, lit = FALSE)
```
<br>
3D Scatter plot은 이해하기 어려운 경우가 많아 이해를 돕기 위하여 2D 데이터를 보여주기도 한다.
수직 세그먼트를 추가해서 점들의 공간위치를 파악하기 쉽도록 한다.
<br>
```{r fig_13_15}
# Function to interleave the elements of two vectors
interleave <- function(v1, v2) as.vector(rbind(v1, v2))
# Plot the points
plot3d(mtcars$wt, mtcars$disp, mtcars$mpg,
xlab = "Weight", ylab = "Displacement", zlab = "MPG",
size = 0.75, type = "s", lit = FALSE)
# Add the segments
segments3d(interleave(mtcars$wt, mtcars$wt),
interleave(mtcars$disp, mtcars$disp),
interleave(mtcars$mpg, min(mtcars$mpg)),
alpha = 0.4, col = "#0000FF")
```
<br>
축과 배경의 외형을 바꾸는 것도 가능하다.
아래 예시는 tick mark를 추가하고 갯수를 바꾸고 label을 붙인 것이다.
<br>
```{r fig_13_16}
# Make plot without axis ticks or labels
plot3d(mtcars$wt, mtcars$disp, mtcars$mpg,
xlab = "", ylab = "", zlab = "",
axes = FALSE,
size = .75, type = "s", lit = FALSE)
segments3d(interleave(mtcars$wt, mtcars$wt),
interleave(mtcars$disp, mtcars$disp),
interleave(mtcars$mpg, min(mtcars$mpg)),
alpha = 0.4, col = "#0000FF")
# Draw the box
rgl.bbox(color = "gray60", # gray60 surface and black text
emission = "gray50", # gray50 emission color
xlen = 0, ylen = 0, zlen = 0)
# Set default color of future objects to black
rgl.material(color = "#000000")
# Add axes to specific sides. Possible values are "x--", "x-+", "x+-", and "x++"
axes3d(edges = c("x--", "y+-", "z--"),
ntick = 6, # Attempt 6 tick marks on each side
cex = 0.75) # Smaller font
# Add axis labels. 'line' specifies how far to set the label from the axis.
mtext3d("Weight", edge = "x--", line = 2)
mtext3d("Displacement", edge = "y+-", line = 3)
mtext3d("MPG", edge = "z--", line = 3)
```
<br>
### 13.8 Adding a prediction surface to a three-dimensional plot
<br>
```{r}
# Given a model, predict zvar from xvar and yvar
# Defaults to range of x and y variables, and a 16x16 grid
predictgrid <- function(model, xvar, yvar, zvar, res = 16, type = NULL) {
# Find the range of the predictor variable. This works for lm and glm
# and some others, but may require customization for others.
xrange <- range(model$model[[xvar]])
yrange <- range(model$model[[yvar]])
newdata <- expand.grid(x = seq(xrange[1], xrange[2], length.out = res),
y = seq(yrange[1], yrange[2], length.out = res))
names(newdata) <- c(xvar, yvar)
newdata[[zvar]] <- predict(model, newdata = newdata, type = type)
newdata
}
# Convert long-style data frame with x, y, and z vars into a list
# with x and y as row/column values, and z as a matrix.
df2mat <- function(p, xvar = NULL, yvar = NULL, zvar = NULL) {
if (is.null(xvar)) xvar <- names(p)[1]
if (is.null(yvar)) yvar <- names(p)[2]
if (is.null(zvar)) zvar <- names(p)[3]
x <- unique(p[[xvar]])
y <- unique(p[[yvar]])
z <- matrix(p[[zvar]], nrow = length(y), ncol = length(x))
m <- list(x, y, z)
names(m) <- c(xvar, yvar, zvar)
m
}
# Function to interleave the elements of two vectors
interleave <- function(v1, v2) as.vector(rbind(v1,v2))
```
```{r fig_13_17}
# Make a copy of the data set
m <- mtcars
# Generate a linear model
mod <- lm(mpg ~ wt + disp + wt:disp, data = m)
# Get predicted values of mpg from wt and disp
m$pred_mpg <- predict(mod)
# Get predicted mpg from a grid of wt and disp
mpgrid_df <- predictgrid(mod, "wt", "disp", "mpg")
mpgrid_list <- df2mat(mpgrid_df)
# Make the plot with the data points
plot3d(m$wt, m$disp, m$mpg, type = "s", size = 0.5, lit = FALSE)
# Add the corresponding predicted points (smaller)
spheres3d(m$wt, m$disp, m$pred_mpg, alpha = 0.4, type = "s", size = 0.5, lit = FALSE)
# Add line segments showing the error
segments3d(interleave(m$wt, m$wt),
interleave(m$disp, m$disp),
interleave(m$mpg, m$pred_mpg),
alpha = 0.4, col = "red")
# Add the mesh of predicted values
surface3d(mpgrid_list$wt, mpgrid_list$disp, mpgrid_list$mpg,
alpha = 0.4, front = "lines", back = "lines")
```
```{r fig_13_18}
plot3d(mtcars$wt, mtcars$disp, mtcars$mpg,
xlab = "", ylab = "", zlab = "",
axes = FALSE,
size = .5, type = "s", lit = FALSE)
# Add the corresponding predicted points (smaller)
spheres3d(m$wt, m$disp, m$pred_mpg, alpha = 0.4, type = "s", size = 0.5, lit = FALSE)
# Add line segments showing the error
segments3d(interleave(m$wt, m$wt),
interleave(m$disp, m$disp),
interleave(m$mpg, m$pred_mpg),
alpha = 0.4, col = "red")
# Add the mesh of predicted values
surface3d(mpgrid_list$wt, mpgrid_list$disp, mpgrid_list$mpg,
alpha = 0.4, front = "lines", back = "lines")
# Draw the box
rgl.bbox(color = "grey50", # grey60 surface and black text
emission = "grey50", # emission color is grey50
xlen = 0, ylen = 0, zlen = 0) # Don't add tick marks
# Set default color of future objects to black
rgl.material(color = "black")
# Add axes to specific sides. Possible values are "x--", "x-+", "x+-", and "x++".
axes3d(edges = c("x--", "y+-", "z--"),
ntick = 6, # Attempt 6 tick marks on each side
cex = .75) # Smaller font
# Add axis labels. 'line' specifies how far to set the label from the axis.
mtext3d("Weight", edge = "x--", line = 2)
mtext3d("Displacement", edge = "y+-", line = 3)
mtext3d("MPG", edge = "z--", line = 3)
```
<br>
### 13.9 Saving a three-dimensional plot
<br>
비트맵 이미지로 3D 결과물을 저장하기 위해서는 `rgl_snapshot()`을 사용한다.
이 함수는 현재 보고 있는 이미지를 보이는 그대로 저장한다.
<br>
```{r}
# plot3d(mtcars$wt, mtcars$disp, mtcars$mpg, type = "s", size = 0.75, lit = FALSE)
#
# rgl.snapshot('3dplot.png', fmt = 'png')
```
<br>
`rgl.postscript()`를 사용하여 저장할 수도 있다.
하지만 Post Script나 PDF는 OpenGL의 많은 기능을 지원하지 않는다.
예를 들어 투명도나 점이나 선의 오브젝트 크기가 화면에 보이는 대로 저장되지 않는다.
<br>
```{r}
# rgl.postscript('3dplot.pdf', fmt = 'pdf')
#
# rgl.postscript('3dplot.ps', fmt = 'ps')
```
<br>
만들어 둔 3D 결과물을 반복적으로 사용하기 위해서는 현재 보고 있는 시점(viewpoint)를 저장해 둘 수 있다.
<br>
```{r}
# Save the current viewpoint
# view <- par3d("userMatrix")
# Restore the saved viewpoint
# par3d(userMatrix = view)
```
<br>
script를 저장하기 위해서 `dput()`를 사용하여 script에 복붙한다.
<br>
```{r}
# dput(view)
```
<br>
`userMatrix`에 저장된 좌표대로 시점이 지정된다.
```{r}
view <- structure(c(0.907931625843048, 0.267511069774628, -0.322642296552658,
0, -0.410978674888611, 0.417272746562958, -0.810543060302734,
0, -0.0821993798017502, 0.868516683578491, 0.488796472549438,
0, 0, 0, 0, 1), .Dim = c(4L, 4L))
# par3d(userMatrix = view)
```
<br>
### 13.10 Animating a three-dimensional plot
<br>
3D 그래프를 자동으로 돌려가며 모든 뷰에서 보고 싶을 때는 `play3d()`를 사용한다.
```{r}
# library(rgl)
# plot3d(mtcars$wt, mtcars$disp, mtcars$mpg, type = "s", size = 0.75, lit = FALSE)
# play3d(spin3d())
```
<br>
default로 z축 방향으로 break command가 들어올 때까지 회전을 하는데 회전 축방향, 회전 속도, 회전 시간을 설정 가능하다.
<br>
```{r}
# Spin on x-axis, at 4 rpm, for 20 seconds
# play3d(spin3d(axis = c(1,0,0), rpm = 4), duration = 20)
```
<br>
이 애니메이션을 저장하기 위해서는 `movie3d()`를 사용하고 사용법은 `play3d()`와 동일하다.
여러 png 파일을 만든 후 합쳐서 영상을 만드는 방식이다.
이미지 처리 프로그램을 사용하여 *.gif로 변환도 가능하다.
<br>
```{r}
# Spin on z axis, at 4 rpm, for 15 seconds
# movie3d(spin3d(axis = c(0,0,1), rpm = 4), duration = 15, fps = 50)
```
<br>
### 13.11 Creating a dendrogram
<br>
```{r}
# Get data from year 2009
c2 <- subset(countries, Year == 2009)
# Drop rows that have any NA values
c2 <- c2[complete.cases(c2), ]
# Pick out a random 25 countries
# (Set random seed to make this repreatable)
set.seed(201)
c2 <- c2[sample(1:nrow(c2), 25), ]
c2
```
```{r}
rownames(c2) <- c2$Name
c2 <- c2[, 4:7]
c2
```
```{r}
c3 <- scale(c2)
c3
```
```{r fig_13_19}
hc <- hclust(dist(c3))
par(mfrow = c(1,2))
# Make the dendrogram
plot(hc)
# with text aligned
plot(hc, hang = -1)
```
<br>
만약 데이터를 scale하지 않으면 아래와 같은 결과가 나온다.
매우 큰 Height value가 나오게 된다.
<br>
```{r fig_13_20}
hc2 <- hclust(dist(c2))
par(mfrow = c(1,2))
# Make the dendrogram
plot(hc2)
# with text aligned
plot(hc2, hang = -1)
```
<br>
### 13.12 Creating a vector field
<br>
<br>
```{r}
isabel
```
<br>
vector field를 그리기 위해서 `geom_segment()`를 사용한다.
<br>
```{r fig_13_21}
islice <- subset(isabel, z == min(z))
islice %>%
ggplot(aes(x = x, y = y)) +
geom_segment(aes(xend = x + vx/50, yend = y + vy/50),
size = 0.25) # Make the line segments 0.25mm thick
```
<br>
이렇게 그려진 vector field는 두가지 문제점을 가지고 있다.
지나치게 고해상도라는 점과 방향을 나타내는 화살표가 표시되지 않았다는 점이다.
데이터의 해상도를 낮추기 위해 `every_n()`이라는 함수를 만들어 매 n번째 데이터만 유지하고 나머지는 버린다.
<br>
```{r}
# Keep 1 out of every 'by' values in vector x
every_n <- function(x, by = 2) {
x <- sort(x)
x[seq(1, length(x), by = by)]
}
```
```{r}
# Keep 1 of every 4 values in x and y
keepx <- every_n(unique(isabel$x), by = 4)
keepy <- every_n(unique(isabel$y), by = 4)
# Keep only those rows where x value is in keepx and y value is in keepy
islicesub <- subset(islice, x %in% keepx & y %in% keepy)
```
```{r fig_13_22}
# Need to load grid for arrow() function
library(grid)
# Make the plot with the subset, and use an arrowhead 0.1 cm long
islicesub %>%
ggplot(aes(x = x, y = y)) +
geom_segment(aes(xend = x + vx / 50, yend = y + vy / 50),
arrow = arrow(length = unit(0.1, "cm")), size = 0.25)
```
<br>
화살표 표시는 짧은 벡터를 표현할 때 더 진하게 보이는 경향이 있어 데이터를 읽을 때 오류를 발생시킬 수 있다.
그래서 속도와 다른 속성에 따라 선두께, 투명도, 색깔을 바꿀 수 있게 만들기도 한다.
아래 예시는 속도에 따른 투명도를 바꾼 예이다.
<br>
```{r fig_13_23}
# The exsiting 'speed' column inclueds the z component.
# We'll calculate speedxy, the horizontal speed.
islicesub$speedxy <- sqrt(islicesub$vx^2 + islicesub$vy^2)
# Map speed to alpha
fig_13231 <-
islicesub %>%
ggplot(aes(x = x, y = y)) +
geom_segment(aes(xend = x + vx / 50, yend = y +vy / 50, alpha = speed),
arrow = arrow(length = unit(0.1, "cm")), size = 0.6) +
labs(subtitle = "map speed to alpha")
# Get USA map data
usa <- map_data("usa")
# Map speed to colour, and set go from "gray80" to "darkred"
fig_13232 <-
islicesub %>%
ggplot(aes(x = x, y = y)) +
geom_segment(aes(xend = x + vx / 50, yend = y +vy / 50, color = speed),
arrow = arrow(length = unit(0.1, "cm")), size = 0.6) +
scale_color_continuous(low = "gray80", high = "#8B0000") +
geom_path(aes(x = long, y = lat, group = group), data = usa) +
coord_cartesian(xlim = range(islicesub$x), ylim = range(islicesub$y)) +
labs(subtitle = "with speed mapped to color")
fig_13231 + fig_13232
```
<br>
`isabel` data는 3차원 데이터가 들어가 있기 때문에 아래와 같이 facet하여 나타낼 수 있다.
각 facet은 매우 작기 때문에 미리 subset을 했다.
<br>
```{r}
# Keep 1 out of every 5 values in x and y, and 1 in 2 values in z
keepx <- every_n(unique(isabel$x), by = 5)
keepy <- every_n(unique(isabel$y), by = 5)
keepz <- every_n(unique(isabel$z), by = 2)
isub <- filter(isabel, x %in% keepx & y %in% keepy & z %in% keepz)
ggplot(isub, aes(x = x, y = y)) +
geom_segment(aes(xend = x+vx/50, yend = y+vy/50, colour = speed),
arrow = arrow(length = unit(0.1,"cm")), size = 0.5) +
scale_colour_continuous(low = "grey80", high = "darkred") +
facet_wrap( ~ z)
```
<br>
### 13.13 Creating a QQ plot
<br>
normal distribution과 비교하기 위해서는 `qqnorm()`을 사용한다.
`qqnorm()`은 숫자형 벡터를 반환하고, `qqline()`은 분포선을 그려준다.
ggplot2에서 QQ line을 그리기 위해서는 `stat_qq()`를 사용하면 된다.
<br>
```{r fig_13_25}
par(mfrow=c(1,2))
# QQ plot of height
qqnorm(heightweight$heightIn)
qqline(heightweight$heightIn)
# QQ plot of age
qqnorm(heightweight$ageYear)
qqline(heightweight$ageYear)
```
<br>
### 13.14 Creating a graph of an empirical cumulative distribution function
<br>
empirical cumulative distribution function(ECDF)를 그리기 위해서 `stat_ecdf()`를 사용한다.
ECDF (경험적 누적 분포 함수)는 데이터 분포의 적합(fit)을 평가하거나 서로 다른 표본들의 분포를 비교할 때 사용한다.
그리고 표본으로부터 모집단 백분위수를 추정할 수 있다.
반복된 시행을 통해 확률변수가 일정한 값을 넘지 않을 확률을 유추하는 함수이다.
<br>
```{r fig_13_26}
fig_13261 <-
heightweight %>%
ggplot(aes(x = heightIn)) +
stat_ecdf()
fig_13262 <-
heightweight %>%