choosing nodes color according to their name

2019-07-22 09:56发布

问题:

I have many igraph objects representing connections among member of different groups. A simple example of my graph data sets is like as follows:

library(igraph)
m<-matrix(data = c("a1_ghj",    "a1_phj",
                   "b2_ghj",    "c1_pht",
                   "c1_ght",    "a1_ghi",
                   "g5_pht",    "d2_phj",
                   "r5_phj",    "u6_pht"), ncol = 2)
))

g<-graph_from_edgelist(m)
g

In the first case, I want to plot this graph regarding that each vertex name that have similar characters after the _ it means that they are in a same group and they should have a same random color. However, as the number of groups in different graphs are various, I don't know how coloring them can be possible in this case. Anyone can help on this issue?

回答1:

You can use sub on the vertex names to get the suffixes. Then treat those as a factor to get different colors for each type of node.

Suffixes = factor(sub(".*_", "", names(V(g))))
Suffixes
 [1] ghj ghi phj pht ghj phj pht phj ght pht
Levels: ghi ghj ght phj pht
plot(g, vertex.color=rainbow(5)[Suffixes])