无法在igraph上绘制网络

时间:2016-11-04 17:25:48

标签: r plot colors igraph

我的二进制图基于边缘列表。每个顶点都是股​​票市场的股票代码(例如:BARC = Barclay's)

    net_full_phase1=graph.edgelist(full_phase1, directed=FALSE)
V(net_full_phase1)$color=V(net_full_phase1)$name
V(net_full_phase1)$size=degree(net_full_phase1)
V(net_full_phase1)$color=gsub("BARC", "slategrey", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("BNP", "blue", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("CBK", "black", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("WFC", "red", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("BKIR", "orange", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("ISP", "purple", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("TPEIR", "lightblue", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("SAB", "yellow", V(net_full_phase1)$color)
V(net_full_phase1)$color=gsub("BCP", "green", V(net_full_phase1)$color) 

plot(net_full_phase1, layout=layout.fruchterman.reingold)

我收到此错误:

  

符号错误(x = coords [,1],y = coords [,2],bg = vertex.color ,:     nom de couleur'WFred'incorrecte

刚跑unique(as.character(V(net_full_phase1)$name)) 结果如下:

"BARC"  "WFC"   "ISP"   "TPEIR" "BCP"   "SAB"   "BNP"   "CBK"   "BKIR" 

我还跑了:table(V(net_full_phase1)$color)结果:

black blue BredP green lightblue purple red redIR slategrey WFred yellow

为什么R不考虑某些颜色为“BredP”,“redIR”,“WFred”?

1 个答案:

答案 0 :(得分:1)

我猜你使用gsub时出了点问题。以下是我接近这个的方式。

# Your vector of unique names 
nms <- c("BARC", "WFC", "ISP" ,"TPEIR" ,"BCP" ,"SAB" ,"BNP", "CBK" ,"BKIR")

使用与示例中相同的顶点名称创建小图

library(igraph)
g <- random.graph.game(length(nms), 0.5)
V(g)$name <- nms

创建查找表以使名称与颜色匹配:这将颜色分配给唯一的顶点名称

lookup <- setNames(
  c("slategrey", "red", "purple", "lightblue", "green", "yellow", "blue", "black", "orange"),
  nms)

# have a look at object
lookup
#        BARC         WFC         ISP       TPEIR         BCP 
# "slategrey"       "red"    "purple" "lightblue"     "green" 
#         SAB         BNP         CBK        BKIR 
#    "yellow"      "blue"     "black"    "orange" 

然后我们可以使用子集([)将它们分配给顶点颜色属性

V(g)$color <- lookup[V(g)$name]
#  have a look at what is produced
V(g)$color 
# [1] "slategrey" "red"       "purple"    "lightblue" "green"    
# [6] "yellow"    "blue"      "black"     "orange"  

哪个产生

enter image description here

PS,我无法重现您的gsub结果:代码可以正常使用

# Your vector of unique names 
nms <- c("BARC", "WFC", "ISP" ,"TPEIR" ,"BCP" ,"SAB" ,"BNP", "CBK" ,"BKIR")

nms = gsub("BARC", "slategrey", nms )
nms = gsub("BNP", "blue", nms )
nms = gsub("CBK", "black", nms )
nms = gsub("WFC", "red", nms )
nms = gsub("BKIR", "orange", nms )
nms = gsub("ISP", "purple", nms )
nms = gsub("TPEIR", "lightblue", nms )
nms = gsub("SAB", "yellow", nms )
nms = gsub("BCP", "green", nms )

# look at result
nms
# [1] "slategrey" "red"       "purple"    "lightblue" "green"     "yellow"    "blue"     
# [8] "black"     "orange"