Labels on only root and terminal vertices in igraph (R)?

北战南征 提交于 2019-12-12 20:09:05

问题


inst2 = c(2, 3, 4, 5, 6) 
motherinst2 = c(7, 8, 2, 10, 11) 
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
df2 = cbind(df2, km)
g2 = graph_from_data_frame(df2)
tkplot(g2)

how would I approach adding labels to exclusively my root and terminal vertices in a graph? I know it would involve this function, but how would you set it up? Assuming the graph object is just called 'g', or something obvious.

vertex.label = 

回答1:


The solution from @eipi1o is good, but the OP says "I'm finding it difficult to apply to my large data set effectively." I suspect that the issue is finding which are the intermediate nodes whose name should be blanked out. I will continue the example of @eipi10. Since my answer is based on his, if you upvote my answer, please upvote his as well.

You can use the neighbors function to determine which points are sources and sinks. Everything else is an intermediate node.

## original graph from eipi10
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

## Identify which nodes are intermediate
SOURCES = which(sapply(V(g), function(x) length(neighbors(g, x, mode="in"))) == 0)
SINKS   = which(sapply(V(g), function(x) length(neighbors(g, x, mode="out"))) == 0)
INTERMED = setdiff(V(g), c(SINKS, SOURCES))

## Fix up the node names and plot
V(g)$name = V(g)
V(g)$name[INTERMED] = ""
plot(g)




回答2:


Using your example graph, we'll identify the root and terminal vertices and remove the labels for other vertices. Here's what the initial graph looks like:

set.seed(2)
plot(g2)

Now let's identify and remove the names of the intermediate vertices

# Get all edges
e = get.edgelist(g2)

# Root vertices are in first column but not in second column
root = setdiff(e[,1],e[,2])

# Terminal vertices are in second column but not in first column
terminal = setdiff(e[,2], e[,1])

# Vertices to remove are not in root or terminal vertices
remove = setdiff(unique(c(e)), c(root, terminal))

# Remove names of intermediate vertices
V(g2)$name[V(g2)$name %in% remove] = ""

set.seed(2)
plot(g2)

Original Answer

You can use set.vertex.attribute to change the label names. Here's an example:

library(igraph)

# Create a graph to work with
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

plot(g)

Now we can remove the labels from the intermediate vertices:

g = set.vertex.attribute(g, "name", value=c(1,rep("", length(2:11)),12:21))

plot(g)



来源:https://stackoverflow.com/questions/47641684/labels-on-only-root-and-terminal-vertices-in-igraph-r

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