如何使用igraph构造二分图? [重复]

时间:2023-02-01 23:53:19

This question already has an answer here:

这个问题在这里已有答案:

I need to create a bipartite graph for consumer-brand relationships.

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

This is my example data:

这是我的示例数据:

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

The following code gives me a network. But I am not sure how I can add a node type attribute to label consumers and brands:

以下代码为我提供了一个网络。但我不确定如何为标签使用者和品牌添加节点类型属性:

    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) 

I would like to create a bipartite graph with edges that connect each consumer with the brand they like. Ideally, the nodes will be labeled with text.

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

Could you show me how to do this using library(igraph)?

你能告诉我如何使用库(igraph)这样做吗?

1 个解决方案

#1


2  

This resource at Shizuka Lab is really useful for exploring bipartite networks in R with igraph. In short:

Shizuka实验室的这个资源对于用igraph探索R中的二分网络非常有用。简而言之:

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)

Gives: 如何使用igraph构造二分图? [重复]

#1


2  

This resource at Shizuka Lab is really useful for exploring bipartite networks in R with igraph. In short:

Shizuka实验室的这个资源对于用igraph探索R中的二分网络非常有用。简而言之:

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)

Gives: 如何使用igraph构造二分图? [重复]