2016年9月22日木曜日

二変数の視覚化:カテゴリー同士

Scatter Plot に曲線フィット」からの続き。

今回は、二変数がどちらもカテゴリーデータの場合の可視化。二変数は「健康保険加入有無」と「婚姻状態」、この関係を bar chart の幾つかの表示方法でプロットする。


stacked bar chart(図 3.15
> ggplot(custdata) + geom_bar(aes(x=marital.stat,fill=health.ins))


side-by-side bar chart(図 3.16
> ggplot(custdata) + geom_bar(aes(x=marital.stat,fill=health.ins), position="dodge")


filled bar chart(図 3.17
> ggplot(custdata) + geom_bar(aes(x=marital.stat,fill=health.ins), position="fill")


filled bar chart with rug(図 3.18
> ggplot(custdata, aes(x=marital.stat)) +
geom_bar(aes(fill=health.ins), position="fill") +
# Set the points just under the y-axis, three-quarters of default size, and make them slightly transparent with the alpha parameter.
geom_point(aes(y=-0.05), size=0.75, alpha=0.3, position=position_jitter(h=0.01))
# Jitter the points slightly for legibility.


複数カテゴリー同士

ここまでは、片方の変数が boolean 値であった。次に、どちらも複数のカテゴリーを持つ場合の視覚化をみる。

変数は「婚姻状態」と「住居状況」。

side-by-side bar chart(図 3.19
> custdata3 <- subset(custdata2, custdata2$housing.type != "<NA>")
> ggplot(custdata3) +
geom_bar(aes(x=housing.type, fill=marital.stat), position="dodge") +
# Tilt the x-axis labels so they don't overlap. You can also use coord_flip() to rotate the graph, as we sawa previously. Some prefer coord_flip() because the theme() layer is complicated to use.
theme(axis.text=element_text(angle=45,hjust=1))

プロットから分かるのは、"Occupied with no rent" がレアケース、Married で "Homeowner with mortgage/loan" が突出して多い、など。

ただ、カテゴリー数がこれ以上増えると side-by-side bar chart はキツくなる。そこで、複数のグラフを使う facet_wrap の登場。ここでは、住居状況ごとにグラフを分けた。

faceted side-by-side bar chart(図 3.20
> ggplot(custdata3) + geom_bar(aes(x=marital.stat), position="dodge", fill="darkgray") +
# Facet the graph by housing.type. The scale="free_y" argument specifies that each facet has an independently scaled y-axis (the default is that all facets have the same sacles on both axes). The argument free_x would free the x-axis scaling, and the argument free frees both axes.
facet_wrap(~housing.type, scales="free_y") +
# As of this writing, facet_wrap is incompatible with coord_flip, so we have to tilt the x-axis labels.
theme(axis.text.x=element_text(angle=45,hjust=1))

次は y 軸のスケールを揃えた場合。
> ggplot(custdata3) + geom_bar(aes(x=marital.stat), position="dodge", fill="darkgray") + facet_wrap(~housing.type) +
theme(axis.text.x=element_text(angle=45,hjust=1))


グラフ化の目的」に続く。

0 件のコメント:

コメントを投稿