« 参議院議員選挙2025年福岡 | トップページ | クラスターのハブの特定:衆院選2024年福岡11区の政党と候補者 »

2026年2月 4日 (水)

2種類のMinimum Spanning Tree (MST)

Screenshot-20260204-at-202358Screenshot-20260204-at-202407

# vegan::spantree

```{r,echo=FALSE,message=FALSE}
# 必要なライブラリの読み込み
library(MASS)    # isoMDS用
library(vegan)   # spantree (MST) 用
library(ggplot2)
library(ggrepel) # ラベル重なり防止用(追加)

# データの読み込み
data_raw <- read.csv("data_PC_fixed.csv", row.names=1)

# 1. データを転置
data_t <- t(data_raw)

# 2. 標準化
data_scaled <- scale(data_t)

# 3. 距離行列の計算(ユークリッド距離)
d <- dist(data_scaled)

# 4. isoMDSによる次元圧縮
set.seed(123)
init_pos <- cmdscale(d, k=2)
mds_res <- isoMDS(d, y = init_pos, k=2)

# MDSの結果をデータフレーム化
mds_df <- as.data.frame(mds_res$points)
colnames(mds_df) <- c("Dim1", "Dim2")
mds_df$label <- rownames(data_t)

# 5. 最小全域木 (MST) の計算
mst_res <- spantree(d)

# MSTの描画用データ(エッジ)の作成
edges <- data.frame(
  x = mds_df$Dim1[2:nrow(mds_df)],
  y = mds_df$Dim2[2:nrow(mds_df)],
  xend = mds_df$Dim1[mst_res$kid],
  yend = mds_df$Dim2[mst_res$kid]
)

# 6. ggplot2による可視化
ggplot(mds_df, aes(x=Dim1, y=Dim2)) +
  # MSTの線を描画
  geom_segment(data=edges, aes(x=x, y=y, xend=xend, yend=yend), 
               color="grey80", linewidth=0.5) +
  # ポイントを描画
  geom_point(aes(color=label), size=3, show.legend = FALSE) +
  # ラベルの表示(geom_textをgeom_text_repelに変更)
  geom_text_repel(aes(label=label), 
                  size=3, 
                  family="HiraKakuProN-W3",
                  max.overlaps = Inf,    # すべてのラベルを強制的に表示
                  box.padding = 0.5,     # ラベル周りの余白
                  point.padding = 0.3,   # 点とラベルの間の余白
                  segment.color = "grey50") + # 引き出し線の色
  # 指定されたテーマの適用
  theme_minimal(base_family="HiraKakuProN-W3") +
  labs(title="政党・候補者の得票傾向によるisoMDSおよび最小全域木",
       subtitle="自治体ごとの得票パターンの類似性に基づく配置",
       x="MDS 第1次元", y="MDS 第2次元")
```

# igraph::mst

```{r,echo=FALSE,message=FALSE}
# 必要なライブラリの読み込み
library(MASS)    # isoMDS用
library(igraph)  # MST計算用
library(ggplot2)
library(ggrepel) # ラベル重なり防止用

# データの読み込み
data_raw <- read.csv("data_PC_fixed.csv", row.names=1)

# 1. データの準備(転置と標準化)
data_t <- t(data_raw)
data_scaled <- scale(data_t)

# 2. 多次元空間での距離行列の計算(全次元の情報を保持)
dist_matrix_full <- dist(data_scaled)

# 3. isoMDSによる次元圧縮(プロット用の2次元座標を作成)
set.seed(123)
# cmdscaleを初期値として使用
init_pos <- cmdscale(dist_matrix_full, k=2)
mds_res <- isoMDS(dist_matrix_full, y = init_pos, k=2)

# 座標データの抽出
mds_coords <- as.data.frame(mds_res$points)
colnames(mds_coords) <- c("Dim1", "Dim2")
rownames(mds_coords) <- rownames(data_t)

# 4. グラフオブジェクトの作成とMSTの計算
g_full <- graph_from_adjacency_matrix(as.matrix(dist_matrix_full), mode = "undirected", weighted = TRUE)
mst_full <- mst(g_full)

# 5. 可視化用データの整形(エッジの座標紐付け)
edges_full <- as_data_frame(mst_full, what = "edges")

edge_coords_full <- data.frame(
  x1 = mds_coords[edges_full$from, 1],
  y1 = mds_coords[edges_full$from, 2],
  x2 = mds_coords[edges_full$to, 1],
  y2 = mds_coords[edges_full$to, 2]
)

# 6. ggplot2 による描画
ggplot() +
  # MSTの枝(ダークグリーンの設定)
  geom_segment(data = edge_coords_full, 
               aes(x = x1, y = y1, xend = x2, yend = y2), 
               color = "darkgreen", alpha = 0.5, linewidth = 0.8) +
  # ノードの描画(ダークレッドの設定)
  geom_point(data = mds_coords, 
             aes(x = Dim1, y = Dim2), 
             color = "darkred", size = 3) +
  # ラベルの描画(ggrepelを使用)
  geom_text_repel(data = mds_coords, 
                  aes(x = Dim1, y = Dim2, label = rownames(mds_coords)),
                  family = "HiraKakuProN-W3", 
                  size = 3, 
                  max.overlaps = 50) + 
  # 軸とテーマの設定
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray80") +
  geom_vline(xintercept = 0, linetype = "dashed", color = "gray80") +
  # アスペクト比を1:1に固定(距離関係を正しく見るため)
  coord_fixed(ratio = 1) +
  theme_minimal(base_family = "HiraKakuProN-W3") +
  labs(
    title = "isoMDSと最小全域木 (MST) : 全次元情報の反映",
    subtitle = paste0("多次元空間での最短距離に基づいたネットワーク (Stress: ", round(mds_res$stress, 2), "%)"),
    x = "MDS Dimension 1",
    y = "MDS Dimension 2"
  )
```

|

« 参議院議員選挙2025年福岡 | トップページ | クラスターのハブの特定:衆院選2024年福岡11区の政党と候補者 »

「分析メモ」カテゴリの記事