如何以正确的顺序放置igraph边缘

时间:2017-01-20 13:59:08

标签: r igraph

我有动物名称的数据框:

df <- data.frame(
    col1 = c("dog", "cat", "bird", "mammal", "avis", "canis", "feline"),
    col2 = c("canis", "feline", "avis", "animal", "animal", "mammal", "mammal"))

library(igraph) 

species <- union(df$col2, df$col1)
df <- df[c('col2', 'col1')]
names(df) <- c('from', 'to')
species <- species[order(species)]
species <- sort(union(df$col2, df$col1))
g <- graph.data.frame(df, directed = TRUE, vertices = species)
plot(g,vertex.size=2, vertex.label.dist=0.5, vertex.color="cyan", 
 edge.arrow.size=0.5, layout=layout.reingold.tilford(g))

运行代码后,我得到了这个图(下图)。在数据框中,前3个元素是"dog", "cat", "bird",而在图表中,它们是"bird", "dog", "cat"。简而言之,单词的顺序颠倒过来,我希望它们按照特定的顺序而不改变数据框。

enter image description here

告诉igraph我希望我的数据表示的顺序是什么,我使用species <- species[order(species)]这个代码行,虽然它适用于具有单个字母的数据框,但它不适用于此代码或任何其他代码使用完整单词的数据框。

2 个答案:

答案 0 :(得分:2)

目前,您的顶点是根据向量species中的顺序排序的。如果没有vertices参数,则顺序是根据两列数据框df中的union元素。

> g <- graph.data.frame(df, directed = TRUE)
> V(g)$name
[1] "canis"  "feline" "avis"   "animal" "mammal" "dog"    "cat"    "bird"  
> g <- graph.data.frame(df, directed = TRUE, vertices = species)
> V(g)$name
[1] "animal" "avis"   "bird"   "canis"  "cat"    "dog"    "feline" "mammal"

要解决您的问题,请根据species两列的并集排序df向量,但先取第二列。这样,"dog", "cat", "bird"序列就会导致species向量。

df <- data.frame(
  col1 = c("dog", "cat", "bird", "mammal", "avis", "canis", "feline"),
  col2 = c("canis", "feline", "avis", "animal", "animal", "mammal",     "mammal"))

library(igraph) 

df <- df[c('col2', 'col1')]
names(df) <- c('from', 'to')
species <- union(df$to, df$from) #NOTE do not sort the vector!
g <- graph.data.frame(df, directed = TRUE, vertices = species)
plot(g,vertex.size=2, vertex.label.dist=0.5, vertex.color="cyan", 
     edge.arrow.size=0.5, layout=layout.reingold.tilford(g))

现在根据物种的顺序对顶点进行排序,首先放置"dog", "cat", "bird"

> species
[1] "dog"    "cat"    "bird"   "mammal" "avis"   "canis"  "feline" "animal"
> V(g)$name
[1] "dog"    "cat"    "bird"   "mammal" "avis"   "canis"  "feline" "animal"

enter image description here

答案 1 :(得分:1)

你的意思是这样吗?

enter image description here

我只是重新安排了数据的顺序,例如:

df <- data.frame(from = c('animal', 'animal', 'mammal', 'mammal', 'avis', 'canis', 'feline'), 
                 to = c('mammal', 'avis', 'canis', 'feline', 'bird', 'dog', 'cat'))

igraph以edgelist的顺序绘制边缘,与数据帧不同:

get.edgelist(g)

这是需要更改的信息。我只创建了小图表,并且总是按照我想要的顺序输入我的数据,但我认为这是调查set.edge.attribute()的内容。