代码之家  ›  专栏  ›  技术社区  ›  Chamil Rathnayake

如何使用igraph构造二部图?[副本]

  •  1
  • Chamil Rathnayake  · 技术社区  · 7 年前

    我需要为消费者品牌关系创建一个二部图。

    这是我的示例数据:

    datf <- data.frame(Consumers = c("A", "B", "C", "D", "E"),
                       Brands = c("Costa", "Starbucks", "Cafe2U", "Costa", "Costa"))
    

    下面的代码为我提供了一个网络。但我不确定如何添加节点类型属性来标记消费者和品牌:

        library(igraph) 
        dat=read.csv(file.choose(),header=TRUE) 
        el=as.matrix(dat) 
        el[,1]=as.character(el[,1])
        el[,2]=as.character(el[,2])
        g=graph.edgelist(el,directed=FALSE) 
    

    我想创建一个带边的二部图,将每个消费者与他们喜欢的品牌联系起来。理想情况下,节点将用文本标记。

    你能告诉我如何使用 library(igraph) ?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Nistara    7 年前

    此资源位于 Shizuka Lab 对于使用 igraph . 简而言之:

    library(igraph)
    
    # Your matrix containing consumer choice by brands
    m = matrix(data = sample(0:1, 25, replace = TRUE), nrow = 5, ncol = 5)
    colnames(m) = c("A", "B", "C", "D", "E")
    rownames(m) = c("Costa", "Starbucks", "Cafe2U", "Petes", "Philz")
    
    # Convert it to a bipartitie network
    bg = igraph::graph.incidence(m)
    bg
    
    # See the vertex attributes 
    V(bg)$type 
    V(bg)$name
    
    # Plot the network
    shape = ifelse(V(bg)$type, "circle", "square") # assign shape by node type
    col = ifelse(V(bg)$type, "red", "yellow") # assign color by node type
    
    plot(bg, vertex.shape = shape, vertex.color = col)
    

    给予: