Plot nodes and edges in a coordinate system using R

烈酒焚心 提交于 2019-12-06 10:04:56

问题


I implemented the FR test here and now I would like to test it by means of visualizing the resulting minimum spanning trees in R. The vertices and edges should be plotted in a coordinate system.

Moreover I want to set the color for every dot (depending on to which sample it belongs) and express a possible third dimension through the size of the dots.

This is what I have got so far:

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:


I also think igraph would be best here...

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))

Here is an example using your data as above, to produce the colours colouring with the coordinate layout system 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")

for plotting a spanning there are also many options, e.g.

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 )

with axes:

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

and use rescale=FALSE to keep original axes scale



来源:https://stackoverflow.com/questions/13432444/plot-nodes-and-edges-in-a-coordinate-system-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!