ggplot(mpg, aes(drv, hwy)) +
geom_point()
geom_point로 그래프를 그렸을 때. 실제 관측값의 개수와는 다르게 데이터가 겹쳐서 원치 않는 방향으로의 정보를 전달해야 하는 상황이 발생할 수 있다. 이럴 때 사용할 수 있는 boxplot과 jittered 그래프를 그려보자.
1. geom_jitter()
ggplot(mpg, aes(drv, hwy)) +
geom_jitter()
jitter 그래프를 사용하면 plot 그래프와는 다르게 같은 값의 데이터를 넓게 퍼트려주어 동일값의 데이터를 한 눈에 확인할 수 있게 한다.
분산시키는 패턴은 매번 다르게 적용되는 것으로 확인된다.
jitter와 비슷한 정보를 제공하는 boxplot 그래프도 있다.
사실 jitter보다는 boxplot을 사용하는 것이 일반적이다.
2. geom_boxplot()
ggplot(mpg, aes(drv, hwy)) +
geom_boxplot()
3. geom_histogram()
ggplot(mpg, aes(hwy)) +
geom_histogram()
ggplot(mpg, aes(displ)) +
geom_histogram(binwidth = 0.5) +
facet_wrap(~drv, ncol = 1)
geom_histogram()에서 binwidth option은 각 bin이 담당하고 있는 구간의 너비를 의미한다. 즉 위에 코드에서는 0.5로 각 bin이 displ 의 0.5 단위를 차지하는 것이다.
다음은 히스토그램과 모양이 비슷한 막대 그래프이다.
4. geom_bar
ggplot(mpg, aes(manufacturer)) +
geom_bar()
default로 geom_bar의 stat option은 count를 채택한다.
stat option에는 다양한 대안이 존재하는데 이번 chpt에서는 identity만을 다루는 것으로 보인다.
예시로 stat에서 identity가 어떻게 적용되는지 확인해 보자.
- geom_bar(stat='identity')
drugs <- data.frame(
drug = c("a", "b", "c"),
effect = c(4.2, 9.7, 6.1)
)
ggplot(drugs, aes(drug, effect)) +
geom_bar(stat = "identity")
stat = 'identity'로 두자 y축이 대상이 count가 아닌 ggplot aesthetic mapping에서 y축의 대상으로 삼았던 effect feature가 그대로
막대그래프의 y축으로 mapping된 것을 확인할 수 있다. identity의 의미대로 위 aesthetic mapping에서 적용한 그대로 stat을 가져가겠다는 것으로 기억하면 좋을 것 같다.
5. geom_line & path
ggplot(economics, aes(date, unemploy / pop)) +
geom_line()
ggplot(economics, aes(date, unemploy / pop)) +
geom_path()
time series를 시각화해야 하는 경우가 있다. 이런 경우 line이나 path그래프를 이용할 수 있다.
6. modifying axes
- option : alpha (투명도)
ggplot(mpg, aes(cty, hwy)) +
geom_point(alpha = 1/3)
geom_point의 option 중 alpha는 점의 투명도를 설정할 수 있도록 한다. 이 투명도 조정을 통해 해당 위치에 얼마나 많은 데이터가 존재하는 지를 직감적으로 판단할 수 있다.
- xlim,ylim
ggplot(mpg, aes(drv,hwy)) +
geom_jitter(width = 0.25) +
xlim('f','r')+
ylim(20,30)
xlim과 ylim으로 축의 범위를 특정 변수가 가지고 있는 value로 설정할 수 있고 숫자로도 시각화할 range를 설정할 수 있다.
단, xlim과 ylim의 경우 설정한 범위 밖에 데이터는 배제시키므로 주의가 필요하다.
'R > Exploratory data analysis' 카테고리의 다른 글
ggplot2::Position scales and axes (0) | 2023.05.21 |
---|---|
ggplot2::geom fuctions (0) | 2023.04.24 |
ggplot2:: geom_smooth() (0) | 2023.04.06 |
ggplot2:: Faceting (0) | 2023.04.06 |
ggplot2::aesthetic mapping (0) | 2023.04.05 |