-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDatadesigner03_ggplot2.Rmd
403 lines (289 loc) · 10.5 KB
/
Datadesigner03_ggplot2.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
---
title: "ggplot2"
author: "Mino"
date: "Friday, February 27, 2015"
output:
html_document:
css: font.css
highlight: tango
---
# ggplot2
- Leland Wilkinson의 "The Grammar of Graphics"를 바탕으로 하여 그래프를 그릴 수 있게 한다
## ggplot2의 장점
- 동일한 문법으로 다양한 그래프를 그릴 수 있다.
- 비교적 쉽게 높은 수준의 그래프를 그릴 수 있다.
- 데이터를 다루고 이해하는데 좋다
------------------
# Grammar of Graphics
ggplot의 구조를 이해하고 사용할 수 있도록 grammar of graphics에서 제시하는 개념들과 함께 정리해보자
## Plot의 구성요소
- A set of layers
- A set of scales
- A coordinate system
- A facetting specification
---------------------
### 1. Layers
- Data
- Aesthetic mappings (aes)
- A geometric object (geom)
- A statistical transformation (stat)
- A position adjustment (position)
### 2. Scales
- Scale은 데이터값이 에스테틱에 대입되는 과정을 조절하고 guide(축과 범례 등)가 어떻게 표시될지를 결정한다
- 보통 ggplot이 알아서 scale을 추가하지만, 원하는 사항에 대해서는 명시해주어야 한다.
### 3. Coordinate systems
- 좌표를 결정하는 에스테틱들이 어떻게 연결되는지를 결정한다
- 기본값은 Cartesian 좌표평면이다
- stat과 geom이 반영된 이후에 변경할 수 있다
---------------------
## how to make a plot?
- length vs width의 산점도(scatter plot)를 그려보자
length | width | trt
-------|-------|------
2 |3 |a
1 |2 |a
4 |5 |b
9 |10 |b
- 산점도(scatter plot)를 그리기 위해 고려해야 할 것은 무엇일까?
- 값들을 점으로 표현 (geom)
- 값은 변형없이 그대로 사용 (stat)
- X, Y축에는 linear scaling (scales)
- Cartesian 좌표평면 적용
- Mapping
- length -> `x`
- width -> `y`
- trt -> `colour`
x |y |colour
---|---|--------
2 |3 |a
1 |2 |a
4 |5 |b
9 |10 |b
- Scales
- 실제로 그래프를 그리는데 사용할 값들로 변경한다
x |y |colour
---|---|--------
25 |11 |red
0 |0 |red
75 |53 |blue
200|300|blue
- Coordinate System
```{r, echo=FALSE}
library(ggplot2)
smp = data.frame(length = c(2,1,4,9), width = c(3,2,5,10), trt=c('a','a','b','b'))
ggplot(smp, aes(x = length, y = width)) + geom_point(aes(colour = trt), size = 10)
```
-------------------------
## ggplot2로 그래프를 그리기 위해 필요한 요소
- Data
- Geometric Object (geom)
- Statistical transformation (stat)
- Scales
- Coordinate system
- (Position Adjustment)
- (facetting)
# ggplot2로 그래프 그리기
## Drawing Layers
앞에서 그래프를 그릴때 필요한 요소들을 언급했다.
해당 요소들을 레이어에 대입시켜서 원하는 그래프를 얻을 수 있다
```{r}
library(ggplot2)
ggplot() +
layer(data = movies,
mapping = aes(x=votes),
geom = "bar",
stat = "bin",
position = "identity")
```
## Drawing Layers with short cut
레이어를 이용해서 직접 그리는 것은 명확하지만 코드가 너무 길어지는 경향이 있다.
레이어에 적용될 요소들을 미리 정의해놓은 함수들을 이용해서 그래프를 그릴 수 있다
각 geom들은 기본적으로 반영하는 stat이 정해져있고, stat도 마찬가지이기 때문에 geom과 stat 중 한 가지만 레이어로 그려지면 그래프를 그리는 것이 가능하다
```{r}
ggplot() +
geom_bar(data = movies, aes(x=votes))
```
stat의 경우 변환을 통해 geom을 그리는 데 필요한 데이터를 생성한다
`stat_bin`의 경우에는
`count` : 관측값의 개수 (기본적으로 count를 사용)
`density` : 밀도 (전체 합이 1)
`ncount` : [0,1]로 스케일된 count
`ndensity` : [0,1]로 스케일된 ndensity
를 생성하는데
이렇게 생성된 데이터를 그래프에서 사용하려면 `..count..`의 형태로 대입해주면 된다
```{r}
ggplot()+stat_bin(data = diamonds, aes(x= price, y = ..count..))
ggplot()+geom_bar(data = diamonds, aes(x= price, y = ..count..))
ggplot()+geom_bar(data = diamonds, aes(x= price, y = ..density..))
ggplot()+geom_bar(data = diamonds, aes(x= price, y = ..ncount..))
ggplot()+geom_bar(data = diamonds, aes(x= price, y = ..ndensity..))
```
## Multiple Layers
여러개의 레이어를 중첩시켜서 그릴 수 있다
```{r}
ggplot() +
geom_point(data = mpg, aes(displ, hwy)) +
geom_smooth(data = mpg, aes(displ, hwy))
```
## Avoid redundancy
공통적으로 반영되는 요소들은 미리 정의해두면 geom이나 stat을 추가할 때 자동적으로 상속받게 된다.
추가되는 geom / stat에서 반영되는 요소들은 상속되지 않는다
또, ggplot을 이용해 만든 결과물들은 객체로 저장하는 것이 가능하다
Mapping되는 부분까지만 객체로 저장한 다음에 다양한 시각화를 시도해 볼 수 있다.
```{r}
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth()
mpgplot <- ggplot(data = mpg, aes(displ, hwy)) # 객체로 저장
mpgplot +
geom_point() +
geom_smooth()
```
## Adding parameters
- geom의 형태나 stat이 적용되는 방법 등을 변경할 수 있다
```{r}
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm") # 회귀선을 직선으로 명시
ggplot(data = mpg, aes(displ, hwy)) +
geom_point(colour = "red") +
geom_smooth()
ggplot(data = mpg, aes(displ, hwy)) +
geom_point(alpha = 0.3) + # 투명도 조절
geom_smooth()
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(linetype = 2) # 선 모양 변경
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(se = FALSE) # 신뢰구간을 표시하지 않는다
ggplot(mtcars, aes(x=factor(cyl))) +
geom_bar(aes(fill = factor(cyl))) # fill은 면적에 색을 채운다
ggplot(mtcars, aes(x=factor(cyl))) +
geom_bar(aes(colour = factor(cyl))) # colour는 stroke색을 변경
ggplot(mtcars, aes(x=factor(cyl))) +
geom_bar(aes(colour = factor(cyl)), size = 2)
```
## Position Adjustment
position을 지정하여 geom이 보여지는 형태를 변경할 수 있다
```{r}
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth()
ggplot(data = mpg, aes(displ, hwy)) +
geom_point(position = "jitter") + # x, y값에 난수를 더해서 점이 겹치지 않게 한다
geom_smooth()
ggplot(data = mpg, aes(displ, hwy)) +
geom_jitter() + # geom_point(position="jitter")와 같다
geom_smooth()
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar()
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar(position="stack") # 누적막대
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar(position="fill") # 막대 길이가 일정한 누적막대(%)
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar(position="dodge") # 각 막대를 옆으로 나열한다
ggplot(diamonds, aes(x=clarity)) +
geom_freqpoly(aes(group = cut, colour = cut),
position = "identity") # 값을 그대로 표현
ggplot(diamonds, aes(x=clarity)) +
geom_freqpoly(aes(group = cut, colour = cut),
position = "stack") # 누적
```
## Scales
스케일 관련함수는 `scale_에스테틱이름_적용방법`으로 이름이 결정된다
위치 스케일의 경우 `xlim()`과 `ylim()` 함수로 그래프에 표현할 값의 범위를 한정지을 수 있다
```{r}
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth() +
xlim(4,6)
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth() +
ylim(20,30)
dia_bar <- ggplot(diamonds, aes(x=cut, fill = cut)) + geom_bar()
dia_bar +
scale_fill_brewer()
```
`RColorBrewer` 패키지를 설치하면 미리 정의된 다양한 색조합을 사용할 수 있다
사용가능한 색 조합의 이름들은 `display.brewer.all()`에서 확인할 수 있다.
```{r, fig.height = 7}
#install.packages("RColorBrewer")
RColorBrewer::display.brewer.all()
```
```{r}
dia_bar +
scale_fill_brewer(palette = "Paired")
dia_bar +
scale_fill_brewer(palette = "Accent")
dia_bar +
scale_fill_brewer(palette = "Accent") +
scale_y_continuous(trans = "log10") # y축에 log10 함수를 적용
dia_bar +
scale_y_continuous(breaks = c(5000, 15000)) # 5000, 15000 구간만 표시
```
## Coordinate system
기본적으로는 cartesian coordinate system이 적용된다
x축과 y축을 바꾸고 싶을 때에는 `coord_flip()`을 적용할 수 있으며
`coord_polar()`를 통해 극좌표계로 변환이 가능하다
```{r}
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth() +
coord_flip() # x, y축 변경
ggplot(data = mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth() +
coord_polar()
```
## Facetting
데이터의 부분 집합들을 하위 그래프로 분리해서 그릴 수 있다
`facet_grid()`또는 `facet_wrap()`을 사용하고 분리할 변수들을 지정한다.
`facet_wrap()`을 사용하면 하위 그래프들이 수평으로 나열된다
`facet_grid()`수직과 수평으로 각각 다른 변수를 지정할 수 있다
```{r}
mtc_point <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
mtc_point +
facet_wrap(~cyl)
mtc_point +
facet_wrap(~cyl, ncol = 2)
mtc_point +
facet_wrap(~cyl+gear)
mtc_point +
facet_grid(gear~cyl)
```
`scales`옵션을 조정하면 축이 서로 다른 면을 만들 수 있다
`"free"` 는 x, y축 눈금을 모두 자유롭게하고, `"free_x"` 또는 `"free_y"`를 통해 각각의 눈금을 자유롭게 둘 수 있다
```{r}
mtc_point +
facet_wrap(~cyl, scales = "fixed")
mtc_point +
facet_wrap(~cyl, scales = "free")
mtc_point +
facet_wrap(~cyl, scales = "free_x")
mtc_point +
facet_grid(gear~cyl, scales = "free_x")
mtc_point +
facet_grid(gear~cyl, scales = "free")
mtc_point +
facet_grid(gear~cyl, scales = "free", space = "free")
```
## theme
그래프의 세부적인 요소들을 조절해서 테마로 저장하는 것이 가능하다
기본적으로 ggplot에서 제공하는 테마도 있으며 패키지로 배포되는 테마들도 있다
아래 예제에서는 ggplot2의 기본 테마와 `ggthemes` 패키지의 테마를 일부 적용해보았다
```{r}
dia_bar + theme_gray()
dia_bar + theme_bw()
dia_bar + theme_classic()
# install.packages("ggthemes")
library(ggthemes)
dia_bar + theme_economist() + scale_colour_economist()
dia_bar + theme_excel()
dia_bar + theme_solarized()
ggplot(diamonds, aes(x = carat, y = price, colour = clarity)) +
geom_point() +
scale_colour_colorblind() # 색각이상자를 위한 색조합
```