상자 그림: 사용법과 예제

상자 그림: 언제 사용하면 좋을까요?

상자 그림은 집단의 중앙값과 사분위수를 비교합니다. 수염 규칙을 명시하며 1.5 × IQR 기준이 자주 쓰입니다.

이 페이지의 내용

표본이 작으면 관측점도 함께 표시합니다. 상자만으로는 반복값이나 표본 수를 알기 어렵습니다.

실행한 예제 그림은 어떤 모습인가요?

아래는 연결된 Bopbun 예제에서 실제 생성한 전체 결과입니다. 입력 데이터와 실행 코드도 함께 제공합니다.

이 글에서는 모의 예제 데이터를 사용합니다.

상자 그림의 전체 예제 출력입니다. 그림 안의 라벨은 모든 언어에서 영어로 유지됩니다.
상자 그림의 전체 예제 출력입니다. 그림 안의 라벨은 모든 언어에서 영어로 유지됩니다.

이 예제는 어떻게 재현하나요?

코드를 쓰기 가능한 폴더에 저장하고 필요한 패키지를 설치한 뒤 Rscript example.R를 실행합니다. 원래 예제의 실행 환경은 R 4.5.3 · ggplot2 4.0.4입니다.

아래는 이 글에서 사용한 코드, 데이터, 실행 결과 파일입니다. 코드를 따라 실행하거나 자신의 결과와 비교할 때 사용할 수 있어요.

  • example.R컴퓨터에서 실행할 수 있는 전체 예제 코드입니다.
  • synthetic.csv예제에 사용한 입력 데이터입니다. 표로 열어 볼 수 있어요.
  • after.png이 글의 설정으로 만든 결과 그림입니다.
  • after.pdf확인하거나 문서에 배치할 수 있는 PDF 결과 파일입니다.
  • 사용 라이선스 · LICENSE.txt코드, 데이터, 그림의 사용 조건과 출처 및 글꼴 라이선스입니다.
전체 소스 코드
# Original example: CC0-1.0.
library(ggplot2)
d <- data.frame(group = factor(c(rep("A", 5), rep("B", 9)), levels = c("A", "B")),
                value = c(1, 2, 2, 2, 20, 1, 2, 3, 4, 5, 6, 7, 8, 20))
base <- ggplot(d, aes(group, value)) +
  scale_x_discrete(labels = c(A = "A (n = 5)", B = "B (n = 9)")) +
  scale_y_continuous(breaks = seq(0, 20, 5)) +
  labs(x = "Group", y = "Response (arbitrary units)") +
  theme_classic(base_size = 11) +
  theme(plot.caption = element_text(size = 8), plot.margin = margin(8, 8, 8, 8))
before <- base + geom_boxplot(width = .45, fill = "white", outlier.colour = "#D55E00") +
  labs(caption = "Default boxplot: whiskers use 1.5 IQR")
hidden <- base + geom_boxplot(width = .45, fill = "white", outlier.shape = NA)
after <- hidden +
  geom_point(position = position_jitter(width = .12, height = 0, seed = 15),
             size = 2, colour = "#17665c") +
  labs(caption = "Boxplot + every observation; horizontal jitter only")
discarded <- base + geom_boxplot(outliers = FALSE)
b <- ggplot_build(before)
a <- ggplot_build(after)
cols <- c("ymin", "lower", "middle", "upper", "ymax")
expected <- data.frame(ymin = c(2, 1), lower = c(2, 3), middle = c(2, 5),
                       upper = c(2, 7), ymax = c(2, 8))
stopifnot(isTRUE(all.equal(b$data[[1]][cols], expected, check.attributes = FALSE)),
          identical(b$data[[1]][cols], a$data[[1]][cols]),
          identical(b$data[[1]]$outliers, list(c(1, 20), 20)),
          nrow(a$data[[2]]) == nrow(d), identical(a$data[[2]]$y, d$value))
summary <- data.frame(group = levels(d$group), n = c(5, 9), expected,
                      IQR = c(0, 4), lower_fence = c(2, -3), upper_fence = c(2, 13),
                      lower_whisker_length = c(0, 2), upper_whisker_length = c(0, 1),
                      outlier_values = c("1;20", "20"))
yrange <- function(plot) ggplot_build(plot)$layout$panel_scales_y[[1]]$range$range
ranges <- rbind(default = yrange(before), hidden = yrange(hidden),
                 discarded = yrange(discarded), raw_overlay = yrange(after))
colnames(ranges) <- c("minimum", "maximum")
stopifnot(identical(unname(ranges["default", ]), c(1, 20)),
          identical(unname(ranges["hidden", ]), c(1, 20)),
          identical(unname(ranges["discarded", ]), c(1, 8)),
          identical(unname(ranges["raw_overlay", ]), c(1, 20)))
ggsave("before.png", before, width = 1200, height = 900, units = "px", dpi = 300, bg = "white")
ggsave("after.png", after, width = 1200, height = 900, units = "px", dpi = 300, bg = "white")
ggsave("after.pdf", after, width = 101.6, height = 76.2, units = "mm", bg = "white")
write.csv(d, "synthetic.csv", row.names = FALSE)
write.csv(summary, "boxplot-summary.csv", row.names = FALSE)
write.csv(data.frame(option = rownames(ranges), ranges), "range-check.csv", row.names = FALSE)
capture.output(sessionInfo(), file = "session-info.txt")
print(summary)
print(ranges)
cat("PASS:14 values; A has zero-length whiskers; B ends at1/8; summaries unchanged; all raw y preserved; hide/discard ranges checked.\n")

다음으로 어떤 자세한 답변을 읽으면 되나요?

연결된 답변에서 이 그림에 사용한 설정을 자세히 설명합니다.

자세한 조작 설명은 현재 영어·간체 중국어·일본어로 제공됩니다. 아래 링크는 영어판을 엽니다.

Boxplot whiskers and quartiles

기술 문서: ggplot2 1

출처·라이선스