[英]Visualize bipartite network graph created using pandas dataframe
我在 csv 文件中有数据,我通过 Pandas 读取它,如下所示
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
sub_data = pd.read_csv('sample.csv')
输出:
user_id item_id rating
0 772 36 3
1 471 228 5
2 641 401 4
3 312 98 4
4 58 504 5
使用此数据创建网络图:
edges = [tuple(x) for x in sub_data[['user_id','item_id']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
B.add_edges_from(edges, label='rating')
使用以下代码绘制图形:
pos=nx.spring_layout(B)
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
我只得到节点。 其中我需要连接节点并将其评级为该连接的标签
我试着运行你写的代码,我能够得到一个二部图。 在您的情况下,我假设 NetworkX 能够呈现类似于我的二部图,但是由于您的图有更多节点,因此边缘不正确可见。 像这样的东西
您可以看到边缘几乎不可见。 如果您还将节点数限制为 10,您可能还会看到边。 如果您有兴趣复制该示例,这里是示例 csv 数据(我在问题中提供的数据中添加了更多点):
,user_id,item_id,rating
0,772,36,3
1,471,228,5
2,641,401,4
3,312,98,4
4,58,504,5
5,67,98,4
6,471,229,3
现在,我知道您想在 Bipartite Layout 中查看图形,两侧各有两组节点。 您需要使用bipartite_layout而不是spring_layout
来实现这一点。
这是完整的代码:
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
sub_data = pd.read_csv('sample.csv')
edges = [tuple(x) for x in sub_data[['user_id','item_id']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
B.add_edges_from(edges, label='rating')
# Now instead of spring_layout, use bipartite_layout
# First specify the nodes you want on left or top
left_or_top = sub_data['user_id'].unique()
# Then create a bipartite layout
pos = nx.bipartite_layout(B, left_or_top)
# Pass that layout to nx.draw
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
另请注意,我已明确将一组节点传递给bipartite_layout
而不是使用此处提到的bipartite_sets ,因为您的图形可能已断开连接,这将导致AmbiguousSolution Error 。 有关更多信息,请阅读此处和此处的文档。
您还可以在此 Google Colab Notebook 中查看完整代码。
更新:如果你想显示边缘,你需要像这样分配它们(你添加评级的代码不正确)
# Extract the ratings while extracting the edges from DF
edges = [tuple(x) for x in sub_data[['user_id','item_id', 'rating']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
# Now assign the ratings correctly to edges
for row in edges:
B.add_edge(row[0], row[1], rating=row[2])
现在使用draw_netwokrx_edge_labels绘制边缘标签:
left_or_top = sub_data['user_id'].unique()
pos = nx.bipartite_layout(B, left_or_top)
# Draw the graph
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
# Get the edge labels for ratings
edge_labels = nx.get_edge_attributes(B,'rating')
# Draw the edge labels
nx.draw_networkx_edge_labels(B, pos, edge_labels=edge_labels)
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.