-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecond.Rmd
More file actions
526 lines (400 loc) · 15.6 KB
/
second.Rmd
File metadata and controls
526 lines (400 loc) · 15.6 KB
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
---
title: "빅데이터 분석의 첫걸음 R코딩"
output: github_document
---
```{r setup, include = F}
knitr::opts_chunk$set(echo = T, fig.align = "center")
```
- Author: 장용식, 최진호
- Book: <https://book.naver.com/bookdb/book_detail.nhn?bid=16324211>
- coding은 example들을 제외하고는 programming으로 넘겼습니다.
---
## 5. Chart programming
_데이터 분석결과를 효과적으로 전달하는 수단으로 차트를 사용한다._
| | | description | 예 |
| ------ | ------ | -------------------------------------------------------- | ------------- |
| 범주형 | 명목형 | 단순히 데이터의 분류 목적 | 성별, 지역 |
| | 순서형 | 데이터 간의 순서가 있다 | 성적 등급 |
| 수치형 | 이산형 | 일정간 간격이 있는 데이터로 절대 0을 갖는다 | 근무년수 |
| | 연속형 | 셀 수 없이 연속적인 값의 데이터로 0이 무를 뜻하지 아니다 | 키, 지진 규모 |
> 범주형 데이터를 비교할 때에는 파이 차트와 바 차트를, 수치형 데이터의 분포를 표현할 때는 산포도, 히스토그램, 박스플롯 등을 이용한다.
```{r message = F}
library(RColorBrewer)
```
### 줄기-잎 그림 (Stem-and-Leaf plot)
```{r rivers}
## rivers
stem(rivers)
stem(rivers, scale = 2)
```
- 기본 줄기수를 sqrt(n)로 정한다고 했던가.
- 현재 줄기는 백의 자리 숫자를 잎은 반올림된 십의 자리 숫자다.
### Pie chart
```{r}
city <- c("서울", "부산", "대구", "인천", "광주", "대전", "울산")
pm25 <- c(18, 21, 21, 17, 8, 11, 25)
colors <- c("red", "orange", "yellow", "green", "lightblue", "blue", "violet")
pie(pm25, labels = city, col = colors, main = "지역별 초미세먼지 농도")
pie(pm25, labels = city, col = colors, main = "지역별 초미세먼지 농도", clockwise = T)
```
- clockwise 옵션을 이용해 시계 방향(default 3시 시작)으로 설정해보았다.
#### addition: palette
```{r}
## library(gdRdriver) ## package에 상관없이 해당 palette를 부를 수 있다.
x <- rep(1, 12)
```
```{r fig.width = 10}
par(mfrow = c(2,3))
pie(x, labels = seq(1, 12), col = rainbow(12))
pie(x, labels = seq(1, 12), col = heat.colors(12))
pie(x, labels = seq(1, 12), col = terrain.colors(12))
pie(x, labels = seq(1, 12), col = topo.colors(12))
pie(x, labels = seq(1, 12), col = cm.colors(12))
```
```{r eval = F}
library(RColorBrewer)
display.brewer.all()
display.brewer.pal(9, name = "Greens")
display.brewer.pal(6, name = "Greens")
```
> display.brewer.pal( ): 지정한 수만큼 해당 이름의 팔레트에서 뽑아온다.
```{r message = F}
library(RColorBrewer)
greens <- brewer.pal(7, "Greens")
pct <- round(pm25/sum(pm25) * 100, 0)
city_label <- paste(city, ", ", pct, '%', sep = '')
```
```{r}
pie(pm25, labels = city_label, col = greens, main = "지역별 초미세먼지 농도", clockwise = T)
```
### Bar chart
```{r}
dept <- c("영업 1팀", "영업 2팀", "영업 3팀", "영업 4팀")
sales01 <- c(4, 12, 5, 8)
```
```{r}
barplot(sales01, names.arg = dept, main = "부서별 영업 실적(1분기)", col = rainbow(length(dept)),
xlab = "부서", ylab = "영업 실적(억 원)", ylim = c(0, 15))
abline(h = mean(sales01), col = "orange", lty = 2)
```
라벨 출력을 해보자.
```{r}
bp <- barplot(sales01, names.arg = dept, main = "부서별 영업 실적(1분기)", col = rainbow(length(dept)),
xlab = "부서", ylab = "영업 실적(억 원)", ylim = c(0, 15))
text(bp, y = sales01, labels = sales01, pos = 3)
```
수평으로 만들어보자.
```{r}
barplot(sales01, names.arg = dept, main = "부서별 영업 실적(1분기)", col = rainbow(length(dept)),
ylab = "부서", xlab = "영업 실적(억 원)", xlim = c(0, 15), horiz = T)
```
스택형 bar plot
```{r}
sales02 <- c(12, 8, 8, 4)
sales <- rbind(sales01, sales02)
sales
```
범례의 위치가 차트 위인 경우, 오른쪽인 경우
```{r}
legend_lbl <- c("1분기", "2분기")
par(mfrow = c(1,2))
barplot(sales, main = "부서별 영업 실적(1~2 분기)", names.arg = dept, xlab = "부서", ylab = "영업 실적(억 원)",
col = c("green", "orange"), legend.text = legend_lbl, ylim = c(0, 30),
args.legend = list(x = "top", ncol = 2))
barplot(sales, main = "부서별 영업 실적(1~2 분기)", names.arg = dept, xlab = "부서", ylab = "영업 실적(억 원)",
col = c("green", "orange"), legend.text = legend_lbl, xlim = c(0, 7), args.legend = list(x = "right"))
```
그룹형 차트 + 차트 밖에 위치한 범례
```{r}
barplot(sales, main = "부서별 영업 실적(1~2 분기)", names.arg = dept, xlab = "부서", ylab = "영업 실적(억 원)",
col = c("green", "orange"), legend.text = legend_lbl, xlim = c(0, 17), args.legend = list(x = "right"),
beside = T)
```
### X-Y plotting
```{r women}
plot(women$height, women$weight, xlab = "키", ylab = "몸무게", main = "키와 몸무게의 변화")
```
pch를 변환시켜보자.
```{r}
plot(women$height, women$weight, xlab = "키", ylab = "몸무게", main = "키와 몸무게의 변화", pch = 23,
col = "blue", bg = "yellow", cex = 1.5)
```
```{r}
plot(women$height, women$weight, xlab = "키", ylab = "몸무게", type = "p")
```
| type | desciption | type | desciption |
| :--: | ----------------------- | :--: | --------------------- |
| p | point | l | line |
| b | point & line | c | only line from b |
| o | alike b | h | show graphical height |
| s | like Gauss's stair plot | S | alike s |
| n | none |
lwd를 다르게 설정해보자.
```{r eval = F}
plot(women$height, women$width, xlab = "키", ylab = "몸무게", type = "l", lty = 1, lwd = 1)
```
축의 출력 범위 제어
```{r}
plot(women$height, women$weight, xlim = c(0, max(women$height)), ylim = c(0 ,max(women$weight)), xlab = "키",
ylab = "몸무게", main = "키와 몸무게의 변화", pch = 23, col = "blue", bg = "yellow", cex = 1.5)
```
- 보면 알겠지만, 축 출력 범위에 따라 그래프의 모양이 다르게 보일 수 있다.
### Histogram
계급 구간을 설정해 막대 수를 줄여보자.
```{r quakes}
par(mfrow = c(1,2))
hist(quakes$mag, col = rainbow(10), xlab = "지진 강도", ylab = "발생 건수", main = "지진 발생 강도의 분포")
hist(quakes$mag, breaks = seq(4, 6.5, 0.5), col = rainbow(10), xlab = "지진 강도", ylab = "발생 건수",
main = "지진 발생 강도의 분포")
```
| 계급 수 공식 | |
| :----------: | --------------------- |
| Sturges | ceil(1 + 3.3\*log(n)) |
| Rice | ceil(2\*n^10) |
확률 밀도로 그린 histogram (default histogram)
```{r}
hist(quakes$mag, freq = F, col = rainbow(10), xlab = "지진 강도", ylab = "확률 밀도", main = "지진 발생 강도의 분포")
lines(density(quakes$mag), lwd = 2)
```
- 확률 밀도이므로 당연히 막대 넓이의 합은 1이다.
### Box plot
```{r}
boxplot(quakes$mag, col = "lightblue", xlab = "지진", ylab = "지진 규모",
main = "지진 발생 강도의 분포")
```
- IF (inner fence): Q3(or Q1) ± 1.5\*(Q3 - Q1)
- OF (outer fence): Q3(or Q1) ± 2\*(Q3 - Q1)
quakes\$mag 다섯 숫자 요약 보기
```{r}
min(quakes$mag); median(quakes$mag); max(quakes$mag)
Q <- quantile(quakes$mag)
Q
Q[3] - Q[1]; IQR(quakes$mag)
fence.upper <- Q[3] + 1.5 * IQR(quakes$mag)
fence.lower <- Q[1] - 1.5 * IQR(quakes$mag)
fence.upper; fence.lower
```
```{r}
quakes$mag[quakes$mag > fence.upper]
max(quakes$mag[quakes$mag <= fence.upper])
quakes$mag[quakes$mag < fence.lower]
```
### 연습용 project
1. CSNow의 거래 데이터를 이용한 분포 분석
```{r}
url <- "https://raw.githubusercontent.com/cran/BTYD/master/data/cdnowElog.csv"
data <- read.csv(url, header = T)
```
```{r}
head(data)
quantity <- data$cds
summary(quantity)
```
```{r}
hist(quantity, xlab = "CD 거래량", ylab = "빈도 수", main = "CD 거래량에 대한 빈도 수 히스토그램")
```
- 다섯 숫자 요약을 보면 최솟값은 1, 제1 사분위수도 1로 왼쪽 끝값에 전체 중 25% 이상이 몰려있다.
- 중간값이 2, 평균이 2.382, 제3 사분위수가 3, 최댓값이 40이다.
- 전체적으로 봉우리 하나를 가지며 오른쪽으로 꼬리가 긴 분포다.
- 언뜻 지수 분포 기본 형태의 제1 사분면과 비슷한 모양이다.
2. 강의 길이에 대한 분포 분석
- 문제 해결 방법: 강 길이 데이터 확인 후, 박스 플랏 출력
```{r}
## data(rivers, package = "datasets")
summary(rivers)
boxplot(rivers, ylab = "강의 길이", main = "강의 길이에 대한 박스 플랏")
points(quantile(rivers)[3] + 1.5*IQR(rivers), col = "blue")
points(quantile(rivers)[3] + 2*IQR(rivers), col = "red")
sum(rivers > quantile(rivers)[3] + 2*IQR(rivers))
```
- 일단 box plot에 끝 수염의 한계가 IF가 아니라 OF였다. lower는 최솟값으로 정해졌다.
- 분포는 데이터가 왼쪽에 몰린 오른쪽으로 꼬리가 긴 모양이다.
- outlier로 판명난 데이터는 총 13개이며 모두 큰 값쪽에 위치한다.
- 데이터의 범위가 큰 편이라 평균값에 영향을 주었을까 걱정했는데, 데이터가 작은 값에 많이 몰려서 그런지 평균은 중심(도화지에 완전한 중심)보다 왼쪽, 작은 값에 위치해 있다.
- 중앙값은 425, 평균은 591.2로 평균이 더 크지만, 분포는 왼쪽으로의 쏠림을 강하게 주장하고 있다. 앞서 말했듯 데이터 분산의 영향으로 보인다.
---
## 6. Animation
> 애니메니션이란 조금씩 다른 일련의 여러 이미지를 빠르게 출력하여 사람들로 하여금 움직임과 변화에 대한 착각을 일으키게 하는 기법이다.
- flip book(1868, 플립 북) → phenakistoscope(1893, 페나키스토스코프) → 영화 필름
### Count down
```{r eval = F}
## install.packages("animation")
library(animation)
```
```{r eval = F}
ani.options(interval = 1)
plot.new()
for (i in 10:0) {
rect(0, 0, 1, 1, col = "yellow")
text_size = 11 - i
text(0.5, 0.5, i, cex = text_size, col = rgb(0, 0, 1, 1))
ani.pause()
}
```
- html animation making이랑 비슷하다. 아마 R 내부에서 web을 이용해 그림을 그리는 거라 그렇겠지.
> ani.options에서 interval로 설정한 시간만큼 ani.pause()로 멈춰있다가 다음으로 넘어간다.
#### 반복문의 이해
```{r}
sum <- 0
for (i in 1:10) sum <- sum + i
print(sum)
```
```{r}
sum <- 0; i <- 1
while (i <= 10) {
sum <- sum + i
i <- i + 1
}; print(sum)
```
```{r}
sum <- 0; i <- 1
repeat {
sum <- sum + i
i <- i + 1
if (i > 10) break
}; print(sum)
```
홀수만을 더해보자.
```{r}
sum <- 0
for (i in 1:10) { if (i %% 2) sum <- sum + i }
print(sum)
```
### Random 막대 그래프
```{r eval = F}
while (T) {
data <- runif(5, 0, 1)
barplot(data, col = rainbow(5))
ani.pause()
}
```
- 균일분포에서 5개의 값을 뽑아 매번 다른 bar plot을 그린다.
### 동전 던지기 확률의 변화 chart
```{r eval = F}
## plot.new()
count <- c(0, 0, 0)
for (i in 1:500) {
coin <- sample(c(0, 1), 2, replace = T)
index <- sum(coin) + 1
count[index] <- count[index] + 1
probability <- count / n
title <- paste("반복 수:", n, "/ 500")
barplot(probability, names.arg = c(0, 1, 2), col = rainbow(3), xlab = "앞면이 나온 횟수", ylab = "확률",
main = title)
Sys.sleep(0.05)
}
```
- 동전 앞, 뒤를 이해하기 더 쉽고, sum() 쓰려고 sample을 0, 1에서 뽑는 것.
- index는 이번에 나온 앞면의 갯수, count는 순서대로 앞면의 수를 축적해온 데이터셋.
- count를 상대빈도(확률)로 바꿔 bar plot을 진행한다.
### 룰렛 돌리기
```{r eval = F}
## install.packages("imager")
library(imager)
img.path <- "C://dump/roulette.JPG"
img <- load.image(img.path)
plot(img)
```
```{r eval = F}
img <- resize(img, size_x = 400L, size_y = 400L)
plot(img, xlim = c(0, 400), ylim = c(0, 400))
plot(img, xlim = c(0, 400), ylim = c(0, 400), axes = F)
```
- plot()을 이용한 출력, 더 깔끔하게 axes도 없애버렸다.
```{r eval = F}
rot.count <- sample(11:20, 1)
rot.count
```
- 각도를 몇 번 줄 건지에 대한 랜덤 수
```{r eval = F}
angle <- 0
for (i in 1:rot.count) {
angle <- angle + 36
title <- paste("룰렛 회전:", i, '/', rot.count)
imrotate(img, angle, cx = 200, cy = 200) %>%
draw_circle(x = 200, y = 30, radius = 30, col = c(1, 0, 0, 0), opacity = 0.5) %>%
plot(axes = F, main = title)
Sys.sleep(0.2)
}
```
- %>%를 통해 새롭게 업데이트된 img를 다음 함수로 넘긴다.
- 매번 할당할 수 없기도 하고, 기호를 추가함으로써 같은 객체를 건드릴 수 있기에 사용한다.
- imrotate()에서 회전 각을 주고, drw_circle()에서 매번 같은 위치에 룰렛의 (선정) 막대를 둔다.
- 이것을 plot을 통해 출력한다.
### Lion King
```{r eval = F}
## install.packages("magick")
library(magick)
lion_bg <- image_read("C://dump/lion_bg.JPG")
lion1 <- image_read("C://dump/lion1.JPG")
lion2 <- image_read("C://dump/lion2.JPG")
```
#### 크기 지정
```{r eval = F}
lion_bg <- image_scale(lion_bg, "600x300!")
lion1 <- image_scale(lion1, "100x50!")
lion2 <- image_scale(lion2, "100x50!")
print(lion_bg, lion1, lion2)
```
#### 위치 바꾸기 연습
```{r eval = F}
img <- image_composite(lion_bg, lion1, offset = "+100+200")
print(img)
```
```{r eval = F}
moving <- 0
x <- -100; y <- 150
while (T) {
## if (x < 0) position <- paste(x, '+', y, sep = '')
## else position <- paste('+', x, '+', y, sep = '')
position = paste('+', x, '+', y, sep = '')
if (moving %% 2 == 0) img <- image_composite(lion_bg, lion1, offset = position)
else img <- image_composite(lion_bg, lion12, offset = position)
print(img)
Sys.sleep(0.3)
if (x > 600) break
moving <- moving + 1
x <- x + 20
}
```
- 초기 위치에서 x 값만 20씩 더해서 움직인다.
- 현재 그림이 0, 0을 기준으로 해서 R-studio에서 친절하게 보이지 않을 때의 움직임도 보여준다고 x가 음수일 때는 x축 0을 기점으로 y축 반전한 것같이 해서 왼쪽으로 가게 했다.
- if의 조건은 offset가 +(-x)가 상식적이지 않아서 나눈 거 같은데 컴퓨터라서 매우 잘 읽는다.
- moving은 뛰어가는 모션을 위해 중간 중간 다른 그림을 보여주기 위함이다.
### 연습용 project
1. 수열 출력: 1 ~ 100 사이의 3의 배수 합
- for을 통해 1:100 중 3의 배수만을 더한다.
```{r}
sum = 0
for (i in 1:100) { if (i %% 3 == 0) sum = sum + i }
print(sum)
```
2. 당구공 굴리기
- 당구대, 당구공 이미지 불러오기 및 크기 지정
- for를 통한 offset의 변화 주기
```{r eval = F}
library(magick)
table <- image_read("C://dump/table.JPG")
ball <- image_read("C://dump/ball.JPG")
table <- image_scale(table, "300x400!")
ball <- image_scale(ball, "40x40!")
```
```{r eval = F}
x <- 0; y <- 0;
flagX = F; flagY = F;
while (T) {
position <- paste('+', x, '+', y, sep = '')
img <- image_composite(table, ball, offset = position)
print(img)
Sys.sleep(0.1)
if (!flagX & x >= 260) flagX = T
elif (flagX & x <= 40) flagX = F
if (!flagY & y >= 360) flagY = T
elif (flagY & y <= 40) flagY = F
if (flagX) x = x - 10
else x = x + 10
if (flagY) y = y - 10
else y = y + 10
}
```
- 사실 R(인지 studio인지)의 친절함을 생각했을 때 table을 바탕으로 깔고 하면, 실제 위치는 이상할지라도 그림은 마치 튕겨나오는 것처럼 보이게 할 수 있다.