[R]Play with ggplot2 Part 02 “error bar”

ggplot2 になれるために、いろいろいじってみる。今回のテーマは error bar。mean は geom_bar/geom_point それぞれでグラフ化。

国立がん研究センターのがん情報サービスで公開されている 5年相対生存率 のデータをもとに、以下をグラフ化。

出典

  • 厚生労働省がん研究助成金「地域がん登録精度向上と活用に関する研究」平成16年度報告書
  • Tsukuma H, Ajiki W, Ioka A, Oshima A, and Research Group of Population-Based Cancer Registry of Japan, Survival of cancer patients diagnosed in 1993-96: collaborative study of population-based cancer registries in Japan, Japanese Journal of Clinical Oncology, 36: 602-607, 2006

部位別がん患者5年相対生存率(主要部位)
geom_bar version

df <- read.csv('main.txt')
head(df)
  Gender Section      N  RSR  SE
1     男  全部位 121454 46.0 0.2
2     男      胃  32195 59.0 0.3
3     男    大腸  21218 69.5 0.4
4     男    結腸  12987 72.3 0.5
5     男    直腸   8231 65.1 0.6
6     男    肝臓  12111 17.0 0.4

p <- ggplot(df, aes(Section, weight=RSR, fill=Section))
limits <- aes(ymax=RSR+SE, ymin=RSR-SE)
p + geom_bar() + coord_flip() + facet_wrap( ~ Gender) + geom_errorbar(limits, width=0.25) +
opts(title="部位別がん患者5年相対生存率(主要部位)[総数 1993年~1996年)]") + ylab("%")

geom_point version

df <- read.csv('main.txt')
df <- transform(df, Section = reorder(Section, -RSR))
limits <- aes(ymax=RSR+SE, ymin=RSR-SE)
p <- ggplot(df, aes(color=Gender, y=RSR, x=Section))
p + geom_point(size=2) + geom_errorbar(limits) +
opts(title="部位別がん患者5年相対生存率(主要部位)[総数 1993年~1996年)]")  + ylab("%") + coord_flip()

部位別がん患者5年相対生存率(詳細部位)

geom_bar version

df <- read.csv('detail.txt')
head(df)
     Section    N  RSR  SE
1 口腔・咽頭 3699 50.9 0.9
2       食道 5820 25.0 0.6
3 胆嚢・胆管 6501 17.5 0.5
4       膵臓 6393  5.5 0.3
5       喉頭 1693 76.7 1.3
6       皮膚 2182 87.5 1.3
p <- ggplot(df, aes(Section, weight=RSR, fill=Section))
limits <- aes(ymax=RSR+SE, ymin=RSR-SE)
p + geom_bar() + coord_flip() + geom_errorbar(limits, width=0.25) +
opts(title="部位別がん患者5年相対生存率(詳細部位)[総数 1993年~1996年)]") + ylab("%")

geom_point version

df <- read.csv('detail.txt')
df <- transform(df, Section = reorder(Section, -RSR))
p <- ggplot(df, aes(color=Section, y = RSR, x = Section))
limits <- aes(ymax=RSR+SE, ymin=RSR-SE)
p + geom_point(size=3) + geom_errorbar(limits) + coord_flip() +
opts(legend.position="none") + opts(title="部位別がん患者5年相対生存率(詳細部位)[総数 1993年~1996年)]") + ylab("%")

メモ

標準誤差には geom_errorbar レイヤーを利用。誤差の範囲(±1SD)を ymax, ymin として指定する。
geom_bar と geom_errorbar のレイヤーの順番を逆にすると、-1SD 分のバーが棒グラフで上書きされるので、バーは片側(+1SD)のみになる。
棒グラフを横に倒すには coord_flip 座標を利用。
棒グラフの上にラベルをかぶせる方法は調べていない。
Section の並び順がグダグダなので、整理したいところ -> geom_point の例にあるように transform{base} で ソートすればよい。
凡例 を削除するには opts(legend.position=”none”) を利用
point+error bar の組合せに出くわしたので追記
—————————————-
もとのグラフでは統計情報として存在する standard error の可視化が落ちていたので、追加したかったというだけ。

Leave a comment