상자그림(boxplot)은 데이터의 분포(퍼져있는 형태)를 직사각형 상자모양으로 표현한 그래프.
상자그림을 보면 분포를 알 수 있기 때문에 평균만 볼 때보다 데이터의 특성을 좀 더 자세히 이해할 수 있음.
ggplot(mpg, aes(x = drv, y = hwy)) +
geom_boxplot()
ggplot(mpg, aes(x = class, y = cty)) +
geom_boxplot()
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mpg_class <- mpg %>%
filter(class %in% c("compact", "subcompact", "suv"))
ggplot(mpg_class, aes(x = class, y = cty)) +
geom_boxplot()
factor() 를 이용하여 수치형 변수를 이산형으로 변환
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
ggplot(birthwt, aes(x = factor(race), y = bwt)) +
geom_boxplot()
ggplot(birthwt, aes(x = factor(race), y = bwt)) +
geom_boxplot(outlier.size = 1.5, outlier.shape = 21)
ggplot(birthwt, aes(x = factor(race), y = bwt)) +
geom_boxplot(notch = TRUE)
## notch went outside hinges. Try setting notch=FALSE.
ggplot(birthwt, aes(x = factor(race), y = bwt)) +
geom_boxplot(outlier.size = 1.5, outlier.shape = 21) +
stat_summary(fun.y = "mean", geom = "point", shape = 23, size = 3, fill = "red")
여러집단의 밀도 추정치 비교
library(gcookbook)
p <- ggplot(heightweight, aes(x = sex, y = heightIn))
p + geom_violin()
p <- ggplot(heightweight, aes(x = sex, y = heightIn))
p + geom_violin() +
geom_boxplot(width = .1, fill = "black", outlier.colour = NA) +
stat_summary(fun.y = median, geom = "point", fill = "white", shape = 21, size = 2.5)
p + geom_violin(trim = FALSE)
각 집단의 곽측개수에 비례하게 면접으로 조절하는 것도 가능. scale=“count”
p + geom_violin(scale = "count")
ggplot(heightweight, aes(x = sex, y = heightIn)) +
geom_boxplot(aes(x = as.numeric(sex) + .2, group = sex), width = .25) +
geom_dotplot(aes(x = as.numeric(sex) - .2, group = sex), binaxis = "y",
banwidth = .5, stackdir = "center") +
scale_x_continuous(breaks = 1:nlevels(heightweight$sex),
labels = levels(heightweight$sex))
## Warning: Ignoring unknown parameters: banwidth
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
p <- ggplot(faithful, aes(x = eruptions, y = waiting))
p + geom_point() + stat_density2d()
..level..을 통해 밀도곡선의 ’높이’를 등고선의 색상에 대입할 수도 있음.
p + stat_density2d(aes(colour = ..level..))
밀도 추정치를 채우기 색상에 대입
p + stat_density2d(aes(fill = ..density..), geom = "raster", contour = FALSE)
점을 나타내고, 밀도추정치를 alpha 에 대입
p + geom_point() +
stat_density2d(aes(alpha = ..density..), geom = "tile", contour = FALSE)
p + stat_density2d(aes(fill = ..density..), geom = "raster", contour = FALSE, h = c(.5, 5))