2016年9月21日水曜日

Histogram と Density Plot:Bar Chart は離散型データの Histogram

対数スケール」からの続き。

「棒グラフ」と「ヒストグラム」の違いとは、

A bar chart is a histogram for discrete data: it records the frequency of every value of a categorical variable. 
bar chart「棒グラフ」は離散型データを表す histogram で、カテゴリー変数の頻度を表す。

次の図 3.6 は、婚姻状態の度数分布。
> ggplot(custdata) + geom_bar(aes(x=marital.stat), fill="gray")

はっきり言って、このグラフは summary より情報量が多いとはいえない。

> summary(custdata$marital.stat)
Divorced/Separated            Married      Never Married            Widowed 
               155                516                233                 96 

何でもかんでも「可視化、可視化」と騒ぐ人は、理解できないかもしれない。

度数の差が大きかったり種類が多い場合は、グラフは効果的。ただし、図 3.7 のように「横向き」が見易い。
> ggplot(custdata) + geom_bar(aes(x=state.of.res), fill="gray") +
# Flip the x and y axes: state.of.res is now the y-axis.
coord_flip() +
# Reduce the size of the y-axis tick labels to 80% of default size for legibility.
theme(axis.text.y=element_text(size=rel(0.8)))

このグラフを更に改良したのが、次の図 3.8 、度数による並べ替え。
ところが、ggplot2 はカテゴリーデータをアルファベット順にプロットするので、度数順には予めデータ加工が必要。

# The table() command aggregates the data by sate of residence - exactly the information the bar chart plots.
> statesums <- table(custdata$state.of.res)
> statef <- as.data.frame(statesums)

# Rename the columns for readability.
> colnames(statef) <- c("state.of.res", "count")

# Notice that the default ordering for the state.of.res variable is alphabetical.
> summary(statef)
     state.of.res     count       
 Alabama   : 1    Min.   :  1.00  
 Alaska    : 1    1st Qu.:  5.00  
 Arizona   : 1    Median : 12.00  
 Arkansas  : 1    Mean   : 20.00  
 California: 1    3rd Qu.: 26.25  
 Colorado  : 1    Max.   :100.00  
 (Other)   :44                    

# Use the reorder() function to set the state.of.res variable to be count ordered. Use the transform() function to apply the transformation to the state.of.res data frame.
> statef <- transform(statef, state.of.res=reorder(state.of.res, count))

# The state.of.res variable is now count ordered.
> summary(statef)
       state.of.res     count       
 Delaware    : 1    Min.   :  1.00  
 North Dakota: 1    1st Qu.:  5.00  
 Wyoming     : 1    Median : 12.00  
 Rhode Island: 1    Mean   : 20.00  
 Alaska      : 1    3rd Qu.: 26.25  
 Montana     : 1    Max.   :100.00  
 (Other)     :44                    
> ggplot(statef) +
geom_bar(aes(x=state.of.res,y=count),stat="identity",fill="grey") +
coord_flip() +
theme(axis.text.y=element_text(size=rel(0.8)))


まとめとして、「一つの変数データの可視化の指針」として、表 3.1 の "Visualizations for one variable" を引用。

Histogram or density plot
Examines data range Checks number of modes Checks if distribution is normal/lognormal Checks for anomalies and outliers 
データの範囲、最頻値の値、分布は normal / lognormal 、異常値や外れ値

Bar chart
Compares relative or absolute frequencies of the values of a categorical variable 
カテゴリー変数の相対的、絶対的な度数比較

0 件のコメント:

コメントを投稿