library(ggplot2)
qplot(diamonds$carat, diamonds$price) # --- ①
qplot(carat, price, data = diamonds) # --- ②
qplot(carat, price, data = diamonds, geom = "point", colour = clarity) # -- ③
qplot(carat, price, data = diamonds, geom = c("point", "smooth"), method = lm) # -- ④
qplot(carat, data = diamonds, geom = "histogram") # -- ⑤
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
R에서 기본으로 제공하는 plot()과 유사한 인터페이스를 제공하는 것이 목적인 함수이다.
첫 번째 인자는 x축의 변수명, 이어서 y축의 변수명이 온다.
data라는 인자로 data.frame형태의 데이터 객체명을 입력 받는다.
이그래프를 코드와 매핑해보면 그 의미를 알 수 있다.
qplot()을 이용한 설명은 더이상 하지 않고, ggplot2를 더 활용하는게 편하다.
ggplot(data = diamonds, aes(x = carat, y = price)) + geom_point(aes(colour = clarity))
test.data <- data.frame(length = c(2, 1, 4, 9), width = c(3, 2, 5, 10), depth = c(4,
1, 15, 80), trt = c("a", "a", "b", "b"))
test.data
## length width depth trt
## 1 2 3 4 a
## 2 1 2 1 a
## 3 4 5 15 b
## 4 9 10 80 b
<그림>
'+'이후의 geom_부분은 좌표계에 레이어를 덧씌우는 역할을 한다.
이런 레이어를 플롯에 올릴 때, 원 데이터는 다음과 같은 변환과정을 통해 레이어 개별적으로 적용 받는다.
1. 미적 매핑
2. 통계적인 변환(stat)
3. 기하객체에 적용(geom)
4. 위치 조정(position adjustment)
1번과 2번 사이에 스케일링 작업이 들어간다는 것을 명심하자.
다음 두 코드는 동일한 그래프를 그린다.
qplot(carat, price, data = diamonds, geom = "point", colour = clarity) #-- ①
ggplot(data = diamonds, aes(x = carat, y = price)) + geom_point(aes(colour = clarity)) #-- ②
gplot()은 '+'없이도 그래프가 생성되지만, ②의 ggplot부분만 실행하면 그래프는 생성 되지 않는다. geom_point()가 실제 레이어 하나를 추가하는 코드이다.
ggplot은 최소 하나 이상의 레이어가 있어야 한다.
s <- ggplot(data = diamonds, aes(x = carat, y = price))
summary(s)
## data: carat, cut, color, clarity, depth, table, price, x, y, z
## [53940x10]
## mapping: x = carat, y = price
## faceting: facet_null()
위와 같은 코드를 출력해 보는 것은 각 코드 조각이 어떻게 작동하고 어떤 데이터를 갖고 있는지 확인하기 위한 좋은 습관이다.
②의 앞부분을 실행한 결과로 나온 객체를 summary한 결과이다. 미적요소를 매핑한 정보가 있는 것을 알 수 있다.
ggplot2의 가장 큰 특징은 ggplot에서 명시한 항목을 뒤의 하위 레이어에서 그대로 이 정보를 받아서 사용하는 것이다. 즉, geom_point(aes(colour = clarity))는 실제로는 geom_point(aes(x = carat, y = price, colour = clarity), data = diamonds)와 같다.
ggplot(data = diamonds, aes(x = carat, y = price)) + geom_point(aes(colour = clarity)) +
geom_smooth() # --- ③
## geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
ggplot(data = diamonds, aes(x = carat, y = price, colour = clarity)) + geom_point() +
geom_smooth() # --- ④
## geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
추가된 레이어에서 미적 요소를 매핑한 코드는 그 다음 레이어로 상속되지 않는다.
③에서는 geom_point()에서 정의된 colour 매핑 정보가 geom_smooth()에 전달되지 않았다.
하지만 ④에서는 colour까지 매핑했더니 의도된 대로 clarity에 따른 회귀 곡선이 그려짐을 알 수 있다.
colour에 매핑된 데이터 기준으로 쪼개 데이터 그룹마다 서로 다른 색생을 입히듯, group 매핑 역시 기준값으로 소그룹을 나눠 stat과 geom을 적용시킨다.
p <- ggplot(data = diamonds, aes(x = carat, y = price))
p + geom_smooth() # --- ⑤
## geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
p + geom_smooth(aes(group = clarity)) # --- ⑥
## geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
그룹 매핑을 하지 않은 ⑤는 전체 데이터를 하나의 회귀 곡선으로 피팅시킨다. ⑥의 코드는 clarity별로 데이터를 나눠 각각의 회귀곡선을 피팅시킨다.