ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

Rでクラスター分析~少年サッカー データ分析~

Rでクラスター分析

この前のを、もう少し丁寧に。

# データファイルのあるフォルダを指定して
setwd("e:/data")
# データ読み込み (header=T は、先頭行が項目名であることを示す)
d <- read.table("stats.txt", header=T)
# 平均が0、分散が1となるよう正規化
d <- scale(d)

# proxy パッケージを使用
library(proxy)
# ggplot2 パッケージを使用
library(ggplot2)
# ggdendro パッケージを使用
library(ggdendro)

#ユークリッド距離行列を求める
d_dist <- dist(d, method="Euclidean")
#ウォード法でコーフェン行列を求める
d_clust <- hclust(d_dist, "ward.D")
#5つのグループに分ける
d_clust.df <- data.frame(
    label = d_clust$labels, 
    cluster = cutree(d_clust, k=5)
)
#樹形図描画情報を取得
d_dendr <- dendro_data(d_clust, type="rectangle")
#グループ分け情報とマージ
d_dendr$labels <- merge(d_dendr$labels, d_clust.df, by="label")

# フォントを準備
windowsFonts(HGKAI=windowsFont("HG正楷書体-PRO"))
windowsFonts(COURIER=windowsFont("Courier New"))

# 色を準備
RED_5    <- "#ff6b6b"
PINK_5   <- "#f06595"
GRAPE_5  <- "#cc5de8" 
VIOLET_5 <- "#845ef7" 
INDIGO_5 <- "#5c7cfa"
BLUE_5   <- "#339af0" 
CYAN_5   <- "#22b8cf" 
TEAL_5   <- "#20c997"
GREEN_5  <- "#51cf66" 
LIME_5   <- "#94d82d" 
YELLOW_5 <- "#fcc419" 
ORANGE_5 <- "#ff922b" 

#樹形図を描画
g <- ggplot()
g <- g + geom_segment(
    data=d_dendr$segment, 
    aes(
        x=x, 
        y=y, 
        xend=xend, 
        yend=yend
    )
)
g <- g + geom_text(
    data=d_dendr$label, 
    aes(
        x=x, 
        y=y, 
        label=label, 
        hjust=0,
        color=factor(cluster)
    ), 
    family="HGKAI",
    size=5
)
#グループごとの色指定
g <- g + scale_colour_manual(values=c(TEAL_5, GRAPE_5, VIOLET_5, PINK_5, BLUE_5))
#横倒し
g <- g + coord_flip()
#逆向き
g <- g + scale_y_reverse()
#タイトルとフォントを設定
g <- g + labs(title="ユークリッド距離 × ウォード法")
g <- g + theme_bw(
    base_size=12, 
    base_family="HGKAI"
)
g <- g + theme(
    legend.position="none",
    plot.title=element_text(
        hjust=0.5
    ),
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.x=element_blank(),
    axis.text.y=element_blank(),
)
#グループごとに枠で囲む
g <- g + annotate("rect", xmin=0.5,  xmax=5.4,  ymin=-0.9, ymax=3.75, alpha=0.03, color=TEAL_5  , fill=TEAL_5  ,size=1)
g <- g + annotate("rect", xmin=5.5,  xmax=8.4,  ymin=-0.9, ymax=3.75, alpha=0.03, color=BLUE_5  , fill=BLUE_5  ,size=1)
g <- g + annotate("rect", xmin=8.5,  xmax=11.4, ymin=-0.9, ymax=3.75, alpha=0.03, color=VIOLET_5, fill=VIOLET_5,size=1)
g <- g + annotate("rect", xmin=11.5, xmax=13.4, ymin=-0.9, ymax=3.75, alpha=0.03, color=GRAPE_5 , fill=GRAPE_5 ,size=1)
g <- g + annotate("rect", xmin=13.5, xmax=17.5, ymin=-0.9, ymax=3.75, alpha=0.03, color=PINK_5  , fill=PINK_5  ,size=1)
print(g)

f:id:fornext1119:20180513084713p:plain
参考:
stackoverflow.com