使用ggplot

时间:2018-06-08 20:30:36

标签: r ggplot2 igraph ggraph ggnetwork

我有以这种形式的分层数据:

df <- data.frame(root=rep("unclustered",22),
  itr1=paste0("1.",c(1,5,1,2,4,1,3,2,5,5,6,9,4,3,4,8,5,7,3,2,10,8)),
  itr2=paste0("2.",c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,10,17,18,19,20,21)),
  itr3=paste0("3.",c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22)),stringsAsFactors = F)

其中描述了数据点的迭代集群分配 - 行。第一列root将所有点分配给根群集,然后每列都是聚类的迭代,它采用前一次迭代的聚类并将其分解为更多的子聚类。

我正在尝试使用树形网络绘制此过程。

我知道使用data.tree,我可以做到:

df$pathString <- do.call(paste,c(df,sep="/"))
df.graph <- data.tree::as.Node(df)
plot(df.graph)

enter image description here

但我正在寻找一些有点发烧友的东西,最好看起来有ggplot

所以我将df.graph转换为igraph对象:

df.igraph <- data.tree::as.igraph.Node(df.graph)

并尝试使用ggraph

library(ggraph)
ggraph(df.igraph, 'igraph', algorithm = 'tree') + 
  geom_edge_link() +
  ggforce::theme_no_axes()

enter image description here

知道如何让ggraph选项包含带有标签的节点,向边缘添加箭头,并且可能以不同方式为每个级别着色?

1 个答案:

答案 0 :(得分:1)

这似乎让我接近:

V(df.igraph)$class <- names(V(df.igraph))

ggraph(df.igraph,layout='tree')+
  geom_edge_link(arrow=arrow(length=unit(2,'mm')),end_cap=circle(3,'mm'))+
  geom_node_label(aes(label=class))+
  theme_void()

enter image description here