如何在R中指定顶点的标签

6

我有一个矩阵如下:

          jerry    peter    king
 jerry     1       0        0    
 peter     0       1        0    
 king      1       1        1              

现在我正尝试用以下代码绘制代表矩阵的图形:

t <- read.table("../data/table.dat");
adjm <- data.matrix(t);
g1 <- graph.adjacency(adjm,add.colnames=NULL);
plot(g1, main="social network", vertex.color="white", edge.color="grey", vertex.size=8,
     vertex.frame.color="yellow");

顶点的标签是id,所以我的问题是如何通过矩阵的dimnames设置顶点的标签? 我已经尝试过以下代码:
vertex.label=attr(adjm,"dimnames")

但是得到了错误的图表。

1个回答

10

有两种方式可以完成这个任务:

  1. When you create the graph object, assign the names to a vertex attribute called label. This is the default that plot.igraph() looks for when plotting.

    g1 <- graph.adjacency(adjm,add.colnames='label')
    
  2. Use the V iterator to extract the name vertex attribute, which is how they are stored if you use add.colnames=NULL.

    plot(g1, main="social network", vertex.color="white", edge.color="grey", vertex.size=8, vertex.frame.color="yellow", vertex.label=V(g1)$name)
    
无论哪种方式都会给您想要的结果。类似于:

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接