이 장에서는 ggplot를 이용하여 데이터를 시각화하는 법을 배울 것이다.
install.packages(“tidyverse”) library(tidyverse)
Q. 엔진이 큰 차가 작은 차보다 연료를 더 많이 소비하는가?
ggplot2::mpg
## # A tibble: 234 x 11
## manufacturer model displ year cyl trans drv cty hwy fl class
## <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
## 1 audi a4 1.8 1999 4 auto(l~ f 18 29 p comp~
## 2 audi a4 1.8 1999 4 manual~ f 21 29 p comp~
## 3 audi a4 2 2008 4 manual~ f 20 31 p comp~
## 4 audi a4 2 2008 4 auto(a~ f 21 30 p comp~
## 5 audi a4 2.8 1999 6 auto(l~ f 16 26 p comp~
## 6 audi a4 2.8 1999 6 manual~ f 18 26 p comp~
## 7 audi a4 3.1 2008 6 auto(a~ f 18 27 p comp~
## 8 audi a4 quat~ 1.8 1999 4 manual~ 4 18 26 p comp~
## 9 audi a4 quat~ 1.8 1999 4 auto(l~ 4 16 25 p comp~
## 10 audi a4 quat~ 2 2008 4 manual~ 4 20 28 p comp~
## # ... with 224 more rows
install.packages(c(“ggplot2”, “plyr”)) library(ggplot2)
library(ggplot2)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
이 플롯은 엔진 크기(displ)와 연비(hwy) 사이에 음의 관계가 있음을 보여준다.
ggplot()을 하면 좌표 시스템이 생성되고 레이어를 추가할 수 있다.
ggplot(data = mpg)를 하면 빈 그래프가 생성
ggplot2의 mapping 인수는 변수들이 시각적 속성으로 어떻게 매핑될지 정의
mapping 인수는 ase()와 쌍을 이루는데 ase()의 x, y인수는 x, y축으로 매핑될 변수를 지정한다.
용어설명
기하객체: geometric object - 줄여서 geom
미적속성: aesthetics property - aes()
ggplot(data = mpg)를 실행하라. 무엇이 나타나는가?
mpg는 행이 몇개인가? 열은 몇 개인가?
?mpg
drv : the type of drive train, where f = front-wheel drive, r = rear wheel drive, 4 = 4wd
hwy 대 cyl의 산점도를 만들어라
ggplot(data = mpg)+
geom_point(mapping = aes(x = hwy, y = cyl))class 대 dvr 산점도를 만들면 어떻게 되는가? 이 플롯이 유용하지 않은 이유는 무엇인가?
ggplot(data = mpg)+
geom_point(mapping = aes(x = class, y = dvr))ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
선형 추세를 벗어나는 점들은 무엇일까?? –> 가설 : 하이브리드 차량이 아닐까?
변수를 추가해서 확인해보자!
class 별로 색깔 구분을 해보자!
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = class))
이를 통해 이상값 중 다수가 2인승 차임을 보여준다.
이 차들은 하이브리드 차가 아닌 스포츠카로 판단된다.
점의 크기로 구분을 해보면 어떨까?
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = class))
- 점의 모양별로 구분을 해보면?
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class))
- ggplot2는 한번에 여섯 개의 모양만 사용
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
ggplot(data = mpg) +
geom_point(
mapping = aes(x = displ, y = hwy, color = "blue")
)
ggplot(data = mpg)
+ geom_point(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow =2)
nrow
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) + facet_grid(. ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = drv, y = cyl))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ .)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
색상 심미성을 쓰지 않고 면분할하면 어떤 이점이 있는가? 단점은 무엇인가? 데이터가 더 크다면 이 균형은 어떻게 바뀌겠는가?
?facet_wrap을 읽어라. nrow의 역할은 무엇인가? ncol은 어떤 일을 하는가? 개별 패널의 배치를 조정할 수 있는 다른 바아법은 무엇인가? facet_grid()에는 nrow, ncol 인수가 왜 없는가?
facet_grid()를 사용할 때, 대개의 경우 고유 수준이 더 많은 변수를 열로 두어야 한다. 왜인가?
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
지옴은 데이터를 나타내기 위해 플롯이 사용하는 기하 객체(geometrix object)를 의미한다.
ggplot2의 모든 지옴 함수는 mapping 인수를 가진다.
점의 sharpe(모양)을 설정할 수 있지만, 선의 ’shape’은 설정할 수 없다.
선의 linetype(선유형)을 설정할 수 있다.
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv))
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = drv)) +
geom_smooth(mapping = aes(linetype = drv))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, color = drv), show.legend = FALSE)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = class)) +
geom_smooth()
library(ggplot2)
library(dplyr)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = class)) +
geom_smooth(data = filter(mpg, class == "subcompact"), se = FALSE)
선 그래프를 그리기 위해 어떤 지옴을 사용하겠는가? 박스 플롯을 그리려면? 히스토그램은? 면적(area)차트는?
머릿속으로 다음의 코드를 실행하고 출력이 어떨지 예측해보라. 그럼 다음 R에서 코드를 실행하고 여러분의 예측을 확인하라.
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point() +
geom_smooth(se = FALSE)
show.legend = FALSE는 어떤 역할을 하는가? 삭제하면 어떻게 되는가? 앞에서 왜 이를 사용했겠는가?
다음의 두 그래프는 다르게 나타나겠는가? 왜 그런가 or 그렇지 않은가?
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
ggplot() +
geom_point(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_smooth(data = mpg, mapping = aes(x = displ, y = hwy))
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth(se = FALSE)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth(mapping = aes(group = drv), se = FALSE)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = drv)) +
geom_smooth(mapping = aes(color = drv), se = FALSE)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = drv)) +
geom_smooth(se = FALSE)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = drv)) +
geom_smooth(mapping = aes(linetype = drv), se = FALSE)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = drv), se = FALSE)
#마지막 그래프는 잘모르겠...
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))
x축은 cut!, 그렇다면 y축은??
?geom_barggplot(data = diamonds) +
stat_count(mapping = aes(x = cut))
그래프에 사용할 새로운 값을 계산하는 알고리즘은 통계적 변환의 줄임말인 스탯(stat)이라고 부른다.
명시적으로 스탯을 사용해야 하는 세가지 이유
기본 스탯을 덮어쓰고 싶을 수 있다.
demo <- tribble( ~cut, ~freq, “Fair”, 1610, “Good”, 4906, “Very Good”, 12082, “Premium”, 13791, “Ideal”, 21551 )
ggplot(data = demo) + geom_bar(mapping = aes(x = cut, y = freq), stat = “identity”)
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = stat(prop), group = 1))
ggplot(data = diamonds) +
stat_summary(
mapping = aes(x = cut, y = depth),
fun.ymin = min,
fun.ymax = max,
fun.y = median)
stat_summary()와 연관된 기본 지옴은 무엇인가? 스탯 함수 대신 이 지옴함수를 사용하여 어떻게 이전 플롯을 다시 생성하겠는가?
geom_col()의 역할은 무엇인가? geom_bar()와 어떻게 다른가?
대부분의 지옴과 스탯은 쌍을 이루어 거의 항상 함께 사용된다. 도움말을 읽고 모든 쌍의 목록을 만들어라. 공통점은 무엇인가?
stat_smooth()는 어떤 변수를 계산하는가? 이 동작을 제어하는 파라미터들은 무엇인가?
우리의 비율 막대 그래프에서 group = 1 이라고 설정했어야 했다. 왜 그런가? 바꿔 말하면 다음 두 그래프의 문제는 무엇인가?
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = ..prop..))
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, colour = cut))
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = cut))
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity))
ggplot(data = diamonds, mapping = aes(x = cut, fill = clarity)) +
geom_bar(alpha = 1/5, position = "identity")
ggplot(data = diamonds, mapping = aes(x = cut, colour = clarity)) +
geom_bar(fill = NA, position = "identity")
ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = clarity), position = "fill")
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
geom_point()
geom_jitter()에서 지터의 정도를 제어하는 파라미터들은 무엇인가?
geom_jitter()에서 geom_count()를 비교 대조하라.
geom_boxplot()의 위치 조정 기본값은 무엇인가? mpg 데이터셋 시각화를 생성하여 이를 표시하라.
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot()
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot() +
coord_flip()
bar <- ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = cut),
show.legend = FALSE,
width = 1) +
theme(aspect.ratio = 1) +
labs(x = NULL, y = NULL)
bar + coord_flip()
bar + coord_polar()
coord_polar()를 사용하여 누적 막대 그래프를 파이 차트로 바꾸라.
labs()는 어떤 동작을 하는가? 설명서를 읽어보자
coord_quickmap()과 coord_map()의 차이점은 무엇인가?
다음 플롯은 도심 연비와 고속도로 연비 사이의 관계에 대해 무엇을 알려주는가? coord_fixed()왜 중요한가? geom_abline()은 어떤 동작을 하는가?
ggplot(data = <데이터>) +
<지옴 함수>(
mapping = aes(<매핑모음>),
stat = <스탯>,
position = <위치>
) +
<좌표계 함수> +
<면분할 함수>