使用R绘制坐标系中的节点和边

时间:2012-11-17 16:30:54

标签: r graph ggplot2 nodes

我实现了FR测试here,现在我想通过在R中可视化生成的最小生成树来测试它。顶点和边应该在坐标系中绘制。

此外,我想为每个点设置颜色(取决于它所属的样本),并通过点的大小表示可能的第三维。

这是我到目前为止所得到的:

library(ggplot2)


nodes <- data.frame(cbind(c("A", "A", "A", "B", "B", "B"), c(1,2,3,8,2,1), c(6,3,1,4,5,6)))
edges <- data.frame(cbind(c("A", "A", "A"), c("A", "B", "B"), c(1,3,2), c(6,1,5), c(2,8,1), c(3,4,6)))


p <- ggplot() + 
    geom_point(nodes, aes(x=nodes[,2], y=nodes[,3])) +
    geom_line(edges)

p

1 个答案:

答案 0 :(得分:2)

我也认为igraph在这里最好......

nodes <- data.frame(a=c("A", "A", "A", "B", "B", "B"), b=c(1,2,3,8,2,1), 
d=c(6,3,1,4,5,6)) 
#cbind made your nodes characters so i have removed it here

edges <- data.frame(a=c("A", "A", "A"), b=c("A", "B", "B"), d=c(1,3,2), 
e=c(6,1,5), f=c(2,8,1), g=c(3,4,6))

以下是使用上述数据的示例,使用坐标布局系统colouring生成颜色coords

library(igraph)

from <- c(rep(edges[,3],3),rep(edges[,4],2),edges[,5])
to <- c(edges[,4],edges[,5],edges[,6],edges[,5],edges[,6],edges[,6])
myedges <- data.frame(from,to)
actors <- data.frame(acts=c(1,2,3,4,5,6,8))
colouring <- sample(colours(), 7) 
sizes <- sample(15,7)
coords<-cbind(x=runif(7,0,1),y=runif(7,0,1))


myg <- graph.data.frame(myedges, vertices=actors, directed=FALSE)
V(myg)$colouring <- colouring
V(myg)$sizes <- sizes

plot(myg,vertex.color=V(myg)$colouring,vertex.size=V(myg)$sizes,
layout=coords,edge.color="#55555533")

用于绘制跨度,还有很多选项,例如

d <- c(1,2,3)

E(myg)$colouring <- "#55555533"
E(myg, path=d)$colouring <- "red"
V(myg)[ d ]$colouring <- "red"

plot(myg,vertex.color=V(myg)$colouring,vertex.size=V(myg)$sizes
,edge.width=3,layout=coords,edge.color=E(myg)$colouring )

有轴:

plot(myg,vertex.color=V(myg)$colouring,vertex.size=V(myg)$sizes
,edge.width=3,layout=coords,edge.color=E(myg)$colouring, axes=TRUE )

并使用rescale=FALSE来保持原始轴的缩放