裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

どういう目的のページ?

2019年12月16日 | ブログラミング

「平均値の棒グラフ」と題して,以下の図が掲示されています。

library(ggplot2)
ggplot(aes(x=Species, y=Sepal.Length, fill=Species), data=iris) +
  stat_summary(fun.y=mean,geom="bar")

何でも図示すればいいというものではありません。

凡例は何のためにあるの?

平均値を示すのに棒グラフというのは妥当なの?

その他,いいたいことは一杯あるけど,「ggplot の初心者のためには,こんな風なことを挙げておけば十分説得力があるんじゃないの?」臭さがふんぷんです。

ggplot のお勉強の前に,統計学や統計図のお勉強をしておく方がよいでしょうという話。

 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

棒グラフをたくさん並べるのは,わかりづらい

2019年12月16日 | ブログラミング

ggplot2tor

gapminder の各大陸,各国,年次別の平均余命のデータ 1704 行,6 列である。

library(tidyverse)
library(gapminder)

gapminder %>%
  mutate(
    year = as.factor(year)
  ) %>%
  ggplot(aes(x = continent, y = lifeExp, fill = year)) +
  stat_summary(fun.y = "mean", geom = "bar",
               alpha = .7, position = position_dodge(0.95)) +
  stat_summary(fun.y = "mean", geom = "point",
               position = position_dodge(0.95),
               size = 1) +
  stat_summary(fun.data = "mean_cl_normal",
               geom = "errorbar",
               position = position_dodge(0.95),
               width = .2)

で,以下のような「綺麗な」図が「簡単に」描ける。

けっしてわかりやすい図とは思えない。

なお,表示されているのは各大陸・年次ごとの数カ国の平均余命の平均値である。

なので,エラーバーを付ける必要性はあまりないかもしれないが,これに関してページの筆者がこんなことを述べている。

the dispersion of life expectancy on the continent of Oceania has increased in recent years. This may be due to mistakes in the data or maybe something has actually changed in life expectancy.

オセアニアの平均余命,近頃伸びが大きいよね。データのミスかもしれないし事実かも知れないが。

いやいや,オセアニアはオーストラリアとニュージーランドの 2 国しかないのであるよ。
図にするのが簡単なあまり,その図を作り上げているデータについて何の注意もしていない。

さて,大規模なデータであるが,必要なのは各大陸別の各国の年次ごとの平均余命である。

素の R で書くと以下のようになる。

df = split(gapminder, gapminder$continent)

で各大陸ごとのデータフレームに分割して,それぞれのデータフレームについて図を重ね描きする。

まずは,土台づくり。

old = par(mgp = c(1.6, 0.6, 0), mar = c(3, 3, 1, 3.5),
    las = 1, tck = -0.01, bty = 'l')
plot(lifeExp ~ year, data = gapminder, type = "n", ylim = c(35, 83),
    ylab = "life expectancy at birth, in years")
col = c("black", "red", "blue", "orange", "brown")

各大陸ごとの処理を for ループで書く。
エラーバーはこの場合は意味がないので,描かない。

for (df2 in df) {
    continent = as.integer(df2$continent[1]) # 大陸は factor なので,対応する整数を取り出す
    mat = matrix(df2$lifeExp, 12) # 国ごとに12年分の平均余命が並んでいるので 12 × 国の数の行列にする
    mean = rowMeans(mat, 2) # 行に対して平均値を取れば 12 年分の平均余命の平均値になる
    lines(seq(1952, 2007, by=5), mean, col=col[continent]) # 折線を描く
    points(seq(1952, 2007, by=5), mean, col=col[continent], pch = 19, cex = 0.5) # マークを付ける
    text(2007, mean[12], df2$continent[1], col=col[continent], xpd=TRUE, pos = 4) # 大陸名を付ける
    title(main = "The Gapminder data on life expectancy, by continent.") # タイトルを付ける
}

以上

やはり,ちゃんと集計結果を見てから図を描かないと,判断を誤るよ。

 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村