« Greenacre's Symbiplot | トップページ | CAに基づくMST、クラスタリング »

2026年2月 4日 (水)

MDS Plot with MST

Screenshot-20260204-at-164158Screenshot-20260204-at-164208


```{r,out.width="100%"}
############################################
### MDS Plot with Minimum Spanning Tree (MST)
############################################
 
 
# 必要パッケージの読み込み
library(ggplot2)
library(ape)
# 【追加】ラベルの重なりを防ぐパッケージ
# install.packages("ggrepel") # もしインストールされていない場合
library(ggrepel) 
 
# 1. データの準備
voting_data <- read.csv("data11ku_PC.csv")
voting_numeric <- voting_data[, 3:ncol(voting_data)]
 
# 2. 規模の影響を除去(得票率に変換)
voting_props <- prop.table(as.matrix(voting_numeric), margin = 1)
party_data_t <- t(voting_props)
colnames(party_data_t) <- voting_data[, 1]
 
# 3. 距離行列とMDSの実行
party_dist <- dist(party_data_t)
party_mds <- cmdscale(party_dist, k = 2)
 
# 4. 最小全域木 (MST) の計算
st <- mst(party_dist)
 
# 5. プロット用データの作成
mds_party_df <- data.frame(
  Dimension1 = party_mds[, 1],
  Dimension2 = party_mds[, 2],
  Name = rownames(party_data_t)
)
 
# MSTの線を描画するためのデータ作成(重複ペアの除去)
edges <- which(as.matrix(st) == 1, arr.ind = TRUE)
edges <- edges[edges[, 1] < edges[, 2], ]
edge_coords <- data.frame(
  x = mds_party_df$Dimension1[edges[, 1]],
  y = mds_party_df$Dimension2[edges[, 1]],
  xend = mds_party_df$Dimension1[edges[, 2]],
  yend = mds_party_df$Dimension2[edges[, 2]]
)
# --------------------------------------------------
 
 
# 6. 描画
ggplot(mds_party_df, aes(x = Dimension1, y = Dimension2)) +
  # MSTの線
  geom_segment(data = edge_coords, aes(x = x, y = y, xend = xend, yend = yend), 
               color = "gray", linetype = "dashed") +
  # 政党の点
  geom_point(color = "red", size = 2) +
 
  # 【変更箇所】geom_text を geom_text_repel に変更
  geom_text_repel(
    aes(label = Name),
    size = 2,
    fontface = "bold",
    family = "HiraKakuProN-W3", # ラベルのフォントも指定
    box.padding = 0.5,          # ラベル周りの余白(調整可能)
    point.padding = 0.3,        # 点とラベルの距離(調整可能)
    force = 10,                 # 重なりを避ける力の強さ(調整可能)
    max.overlaps = Inf          # すべてのラベルを表示しようとする設定
  ) +
 
  # 表示範囲とテーマの設定
  expand_limits(
    x = c(min(mds_party_df$Dimension1) * 1.3, max(mds_party_df$Dimension1) * 1.3),
    y = c(min(mds_party_df$Dimension2) * 1.3, max(mds_party_df$Dimension2) * 1.3)
  ) +
  coord_cartesian(clip = "off") +
  theme_minimal(base_family = "HiraKakuProN-W3") +
  theme(
    plot.margin = margin(t = 60, r = 60, b = 40, l = 60),
    plot.title = element_text(size = 12, face = "bold", vjust = 4)
  ) +
  labs(
    title = "MDS Plot with Minimum Spanning Tree (MST)",
    subtitle = "Lines connect candidates with the most similar voting patterns",
    x = "Coordinate 1",
    y = "Coordinate 2"
  )
```
 
 
```{r}
############################################
### MDS Plot with Minimum Spanning Tree (MST)
############################################
 
 
# 必要パッケージの読み込み
if (!require("ape")) install.packages("ape")
library("ape")
 
# 1. データの準備
voting_data <- read.csv("data11ku_PC.csv")
voting_numeric <- voting_data[, 3:ncol(voting_data)]
 
# 2. 得票率に変換して転置(規模の差を除去)
voting_props <- prop.table(as.matrix(voting_numeric), margin = 1)
party_data_t <- t(voting_props)
colnames(party_data_t) <- voting_data[, 1] # 列名(自治体略称)
 
# 3. 距離計算とMDSの実行
party_dist <- dist(party_data_t)
party_mds <- cmdscale(party_dist, k = 2)
 
# 座標を x, y に格納
x <- party_mds[, 1]
y <- party_mds[, 2]
 
# 4. 最小全域木 (MST) の計算
st <- mst(party_dist)
 
# 5. プロットの作成

# xlim と ylim を 1.5倍 程度に広げて余白を確保
plot(x, y, 
     xlab = "Coordinate 1", 
     ylab = "Coordinate 2",
     main = "MDS with MST (Base R version)",
     xlim = range(x) * 1.5, 
     ylim = range(y) * 1.5, 
     type = "n") # type="n" でまずは点や線を描かずに枠だけ作成
 
# 最小全域木の線を描画(テキストのループ処理を適用)
for (i in 1:nrow(party_data_t)) {
    w1 <- which(st[i, ] == 1)
    segments(x[i], y[i], x[w1], y[w1], col = "gray", lty = 2)
}
 
# 点とラベルの描画
points(x, y, pch = 21, bg = "red", cex = 2)
text(x, y, labels = rownames(party_data_t), pos = 3, cex = 0.7, font = 2)
```

 

|

« Greenacre's Symbiplot | トップページ | CAに基づくMST、クラスタリング »

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