24

Didzis Elferts は、ggplot2 と ggdendro を使用してデンドグラムをプロットする方法を示しました。

ラベル付きのRの水平デンドログラム

コードは次のとおりです。

labs = paste("sta_",1:50,sep="") #new labels
rownames(USArrests)<-labs #set new row names
hc <- hclust(dist(USArrests), "ave")

library(ggplot2)
library(ggdendro)

#convert cluster object to use with ggplot
dendr <- dendro_data(hc, type="rectangle") 

#your own labels are supplied in geom_text() and label=label
ggplot() + 
  geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) + 
  geom_text(data=label(dendr), aes(x=x, y=y, label=label, hjust=0), size=3) +
  coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
  theme(axis.line.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_rect(fill="white"),
        panel.grid=element_blank())

さまざまなクラスターに色を付ける方法を知っている人はいますか? たとえば、2 つのクラスター (k=2) を色付けしたいですか?

4

5 に答える 5

17

回避策として、 でクラスター オブジェクトをプロットしplot()、関数を使用rect.hclust()してクラスターの周囲に境界線を描画します (クラスターの数は引数で設定されますk=)。の結果がrect.hclust()オブジェクトとして保存される場合、各リスト要素に各クラスターに属する観測が含まれる観測のリストが作成されます。

plot(hc)
gg<-rect.hclust(hc,k=2)

これで、このリストをデータフレームに変換できます。ここで、列clustにはクラスターの名前 (この例では 2 つのグループ) が含まれます。名前は、リスト要素の長さに応じて繰り返されます。

clust.gr<-data.frame(num=unlist(gg),
  clust=rep(c("Clust1","Clust2"),times=sapply(gg,length)))
head(clust.gr)
      num  clust
sta_1   1 Clust1
sta_2   2 Clust1
sta_3   3 Clust1
sta_5   5 Clust1
sta_8   8 Clust1
sta_9   9 Clust1

新しいデータ フレームは、オブジェクトlabel()の情報(結果)とマージされます。dendrdendro_data()

text.df<-merge(label(dendr),clust.gr,by.x="label",by.y="row.names")
head(text.df)
   label  x y num  clust
1  sta_1  8 0   1 Clust1
2 sta_10 28 0  10 Clust2
3 sta_11 41 0  11 Clust2
4 sta_12 31 0  12 Clust2
5 sta_13 10 0  13 Clust1
6 sta_14 37 0  14 Clust2

デンドログラムをプロットするときtext.dfは、ラベルを追加し、色にgeom_text()clustを使用します。

ggplot() + 
  geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) + 
  geom_text(data=text.df, aes(x=x, y=y, label=label, hjust=0,color=clust), size=3) +
  coord_flip() + scale_y_reverse(expand=c(0.2, 0)) + 
  theme(axis.line.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_rect(fill="white"),
        panel.grid=element_blank())

ここに画像の説明を入力

于 2014-01-31T15:41:45.063 に答える