0
2

More than 5 years have passed since last update.

箱ひげ図の「ひげ」の上端と下端の値を知りたいので関数を自作した

Last updated at Posted at 2019-07-21

この記事を書いたきっかけ

統計を勉強し始めると棒グラフにも色々なグラフがあることを知ります。
その中でも初期に出てくるであろう箱ひげ図があります。

スクリーンショット 2019-07-21 23.28.32.png

箱ひげ図は「最小値, 第一四分位数, 中央値, 第三四分位数, 最大値」を示します。
ただ上記のグラフのようにひげは外れ値がなければひげの上端・下端が最大・最小値になるのですが、男性のように外れ値があると髭の長さは上記のどれにも当てはまりません。

Rやpythonではコードを書くと自動的にひげ(あれば外れ値も)をつけてくれますがひげの上端(下端)の値が実際何なんなのか?が気になったのでRで調べてみました。

ひげの定義

ひげの定義をggplot2geom_boxplotのヘルプで確認します。

?geom_boxplot

A box and whiskers plot (in the style of Tukey)

(中略)
The upper whisker extends from the hinge to the largest value no further than 1.5 * IQR from the hinge (where IQR is the inter-quartile range or distance between the first and third quartiles). The lower whisker extends from the hinge to the smallest value at most 1.5 * IQR of the hinge. Data beyond the end of the whiskers are called "outlying" points and are plotted individually.

(要約)
ひげの上端は箱の上端 + 1.5 * IQRの範囲内にあるデータの最大値
ひげの下端は箱の下端 - 1.5 * IQRの範囲内にあるデータの最小値
IQRは箱の上端 - 箱の下端
ひげの外にあるデータは"外れ値"として個別に表示

Rで関数を作ってみる

wisker <- function(x){
  x_iqr <- IQR(x) #IQR関数でIQRを求める
  wisker_max <- quantile(x, 0.75) + IQR(x) * 1.5 # 上端のひげの取りうる最大値を求める
  wisker_higher <- max(x[x <= wisker_max]) # ひげの範囲内の最大値を求める
  wisker_min <- quantile(x, 0.25) - IQR(x) * 1.5 # 下端のひげの取りうる最小値を求める
  wisker_lower <- min(x[x >= wisker_min]) # ひげの範囲内の最小値を求める
  wisker <- c(wisker_low = wisker_lower, wisker_high = wisker_higher) # 名前をつけて結果をwiskerという変数に入れる
  print(wisker)
}

実際のデータで試してみる

架空のデータを作る

n_male <- 130
n_female <- 70
set.seed(2019)
height <- round(c(rnorm(n_female, 157, 5), rnorm(n_male, 173, 10)), 0)
sex <- c(rep("female", n_female), rep("male", n_male))
dat <- data.frame(height, sex)

箱ひげ図をggplot2geom_boxplotで書く

# tidyverseパッケージをインストールしていない場合は先にインストール
install.packages("tidyverse") 

# インストール後tidyverseパッケージを読み込む
library(tidyverse) # tidyverseパッケージのインストール

# 箱ひげ図を書く
ggplot(data = dat, aes(x = sex, y = height))+
  geom_boxplot()

スクリーンショット 2019-07-21 23.12.21.png

自作のwisker関数を使ってみる

# 女性
wisker(dat$height[sex == "female"])
# 男性
wisker(dat$height[sex == "male"])

まとめ(結果)

スクリーンショット 2019-07-21 23.15.48.png

外れ値がない女性はひげの上端・下端が最大・最小値になり、外れ値のある男性はグラフのひげと同じ位置を示してくれました。

おしらせ

統計・プログラミング未経験者向けのRのサイトを運営しています。
独学で始める統計×データサイエンス

ggplot2を使った箱ひげ図の作り方は【3-6】Rのggplot2で箱ひげ図を作るgeom_boxplot関数で紹介しています。

参考

4-3. 外れ値検出のある箱ひげ図(統計web)

0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2