2016年9月21日水曜日

二変数の視覚化:Line より Scatter

本投稿は、Nina Zumel, John Mount 著 "Practical Data Science with R" の第 3"3.2.2. Visually checking relationships between two variables" をもとにした。

Practical Data Science With R
Practical Data Science With R
Nina Zumel John Mount

前回の「Histogram と Density Plot」は「変数が一つ」の場合で、今回は「変数が二つ」。変数が二つの場合の例は、前回までのデータ項目では「年齢と収入」「婚姻状態と健康保険加入状況」など。そして、それらの「関係の強さ」を視覚化する方法をみていく。


Line Plots

「二変数の関係」の代表格は、「x の値から y の値が決まる」関数だろう。
# First, generate the data for this example. The x variable is uniformly randomly distributed between 0 and 1.
> x <- runif(100)
# The y variable is a quadratic function of x.
> y <- x^2 + 0.2*x
> ggplot(data.frame(x=x,y=y), aes(x=x,y=y)) + geom_line()

この図 3.9 は「ランダムな x 値に対して y 値が導ける」という clearnly related「明確な関係」にある。ところが、

When the data is not so cleanly related, line plots aren’t as useful.

つまり「cleanly related でない」場合、例えば「x = 1 のとき、y が 2 や 3 になる」など。年齢と収入の関係も、単純な関数では表せない。世の中に「勝利の方程式」なんて存在かのごとく...(笑)

私見だが、ここで示唆してるのは

いきなり「線形回帰」するのは良くない

ということ。線形回帰は、単純で分かりやすい分析手法ではある。しかし「そんな単純な関係性ばかりじゃない」し、何よりも「線形回帰に拘りすぎて分析を誤る」リスクを高めるだけ。「線形じゃない」という分析結果には意味がないしね(笑)


Scatter Plots

そんな、「不確かな関係」を探るのに便利なのが scatter plot 。その前に、理にかなっているデータのみで、年齢と収入の相関具合をみる。

# Only consider a subset of data with reasonable age and income values.
> custdata2 <- subset(custdata, (custdata$age > 0 & custdata$age < 100 & custdata$income > 0))
> cor(custdata2$age, custdata2$income)
[1] -0.02240845

値は小さいが、意外にもマイナス値になった。

これをプロットしたのが次。
> ggplot(custdata2, aes(x=age,y=income)) + geom_point()

二変数の関係は掴みやすくするため、頻度が少ない 2e+05 以上の値を無視したのが、次の図 3.10
> c1 <- "Income tends to increase in this range."
> c2 <- "And it tends to decrease in this range."
> c3 <- "But the relationship is hard to see."
> myarrow <- arrow(ends = "both", type = "closed", length = unit(5,"mm"))
> ggplot(custdata2, aes(x=age,y=income)) + geom_point() + ylim(0,200000) +
geom_segment(aes(x=10,y=195000,xend=53,yend=195000),size=0.5,color="#56B4E9",arrow=myarrow) +
geom_segment(aes(x=55,y=180000,xend=95,yend=180000),size=0.5,color="#56B4E9",arrow=myarrow) +
geom_text(data=data.frame(),aes(x=10,y=200000),label=c1,hjust=0,color="#56B4E9",fontface="bold") +
geom_text(data=data.frame(),aes(x=55,y=185500),label=c2,hjust=0,color="#56B4E9",fontface="bold") +
geom_text(data=data.frame(),aes(x=40,y=159000),label=c3,hjust=0,color="#56B4E9",fontface="bold")
 警告メッセージ: 
Removed 32 rows containing missing values (geom_point). 
単に、「32 件を無視した」という警告メッセージ。これが全件数に対して多ければ、幅を広げること。

プロット中のコメントの通り「50 歳までは増加、それから減少」と、大まかな見方もできるが、それで「年齢と収入の関係」が明確になったとはいえない。

次回、このプロットにフィットするような曲線を探す。

Scatter Plot に曲線フィット」に続く。

0 件のコメント:

コメントを投稿