【问题标题】:Bipartite graph projection with nodes as edge attributes以节点为边属性的二分图投影
【发布时间】:2021-10-24 20:47:27
【问题描述】:

我有一个二分图,我希望这个图的投影具有边缘属性,记录它们通过哪些节点连接。例如:

require(igraph)
set.seed(123)
g <- sample_bipartite(5, 5, p =.5)
V(g)$name <- c(letters[1:5], 1:5)
g1 <- bipartite_projection(g)[[1]]
g2 <- bipartite_projection(g)[[2]]

par(mfrow = c(1, 3))
plot(g,
     vertex.shape = ifelse(V(g)$type == FALSE, "square", "circle"),
     vertex.color = ifelse(V(g)$type == FALSE, "gold", "tomato"),
     main = "Bipartite")
plot(g1,
     main = "Projection 1")
plot(g2,
     main = "Projection 2")
par(mfrow = c(1, 1))

我希望我手动添加到绘图中的信息位于网络对象中。它很容易在 igraph 中完成吗?谢谢。

【问题讨论】:

    标签: r igraph sna


    【解决方案1】:

    bipartite_projection

    如果你真的不想使用bipartite_projection,你可以尝试定义你的自定义函数f,如下所示:

    f <- function(gp) {
      df <- get.data.frame(gp)[1:2]
      df$lbl <- apply(
        df,
        1,
        function(v) {
          max(do.call(intersect, unname(lapply(v, function(x) names(neighbors(g, x))))))
        }
      )
      res <- graph_from_data_frame(df, directed = FALSE)
      plot(res, edge.label = E(res)$lbl)
    }
    
    f(g1)
    f(g2)
    

    给了

    没有bipartite_projection

    下面是一个不使用bipartite_projection的选项(以g1为例,g2可以通过类似的方式获得)

    g1 <- simplify(
      graph_from_data_frame(
        do.call(
          rbind,
          lapply(
            Filter(
              function(x) nrow(x) > 1,
              split(get.data.frame(g), ~to)
            ),
            function(d) {
              with(
                d,
                cbind(data.frame(t(combn(from, 2))), weight = unique(to))
              )
            }
          )
        ),
        directed = FALSE
      ),
      edge.attr.comb = "max"
    )
    

    plot(g1, edge.label = E(g1)$weight) 给了

    【讨论】:

      【解决方案2】:

      首先,我制作了as.edgelist 结果的数据框,然后用paste0 计算了一个标签。接下来,我使用edge_attr 命令将标签写入图形对象。

      el<-igraph::as_edgelist(g);el<-as.data.frame(el)
      el$lab<-paste0(el$V1,"_",el$V2)
      edge_attr(g,"label")<-el$lab
      
      E(g)$label
      set.seed(232)
      plot(g,
         edge.label.dist=.3,
         edge.label.color="blue",
         margin=-0.4,
         layout=layout.fruchterman.reingold)
       
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-15
        • 2013-04-06
        • 1970-01-01
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        相关资源
        最近更新 更多