我在 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而不是 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如前所述here ,因为您的图形可能已断开连接,这会导致 AmbiguousSolution Error .有关详细信息,请阅读文档 here和 here .
您还可以在this 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)
引用资料:
关于python - 可视化使用 pandas 数据框创建的二分网络图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100006/