python networkx 边权重_Python / NetworkX:通过边缘占有频率向边缘添加权重

I have a MultiDiGraph created in networkx for which I am trying to add weights to the edges, after which I assign a new weight based on the frequency/count of the edge occurance. I used the following code to create the graph and add weights, but I'm not sure how to tackle reassigning weights based on count:

g = nx.MultiDiGraph()

df = pd.read_csv('G:\cluster_centroids.csv', delimiter=',')

df['pos'] = list(zip(df.longitude,df.latitude))

dict_pos = dict(zip(df.cluster_label,df.pos))

#print dict_pos

for row in csv.reader(open('G:\edges.csv', 'r')):

if '[' in row[1]: #

g.add_edges_from(eval(row[1]))

for u, v, d in g.edges(data=True):

d['weight'] = 1

for u,v,d in g.edges(data=True):

print u,v,d

Edit

I was able to successfully assign weights to each edge, first part of my original question, with the following:

for u, v, d in g.edges(data=True):

d['weight'] = 1

for u,v,d in g.edges(data=True):

print u,v,d

However, I am still unable to reassign weights based on the number of times an edge occurs (a single edge in my graph can occur multiple times)? I need to accomplish this in order to visualize edges with a higher count differently than edges with a lower count (using edge color or width). I'm not sure how to proceed with reassigning weights based on count, please advise. Below are sample data, and links to my full data set.

Data

Sample Centroids(nodes):

cluster_label,latitude,longitude

0,39.18193382,-77.51885109

1,39.18,-77.27

2,39.17917928,-76.6688633

3,39.1782,-77.2617

4,39.1765,-77.1927

5,39.1762375,-76.8675441

6,39.17468,-76.8204499

7,39.17457332,-77.2807235

8,39.17406072,-77.274685

9,39.1731621,-77.2716502

10,39.17,-77.27

Sample Edges:

user_id,edges

11011,"[[340, 269], [269, 340]]"

80973,"[[398, 279]]"

608473,"[[69, 28]]"

2139671,"[[382, 27], [27, 285]]"

3945641,"[[120, 422], [422, 217], [217, 340], [340, 340]]"

5820642,"[[458, 442]]"

6060732,"[[291, 431]]"

6912362,"[[68, 27]]"

7362602,"[[112, 269]]"

Full data:

UPDATE

I was able to solve, at least temporarily, the issue of overly disproportional edge widths due to high edge weight by setting a minLineWidth and multiplying it by the weight:

minLineWidth = 0.25

for u, v, d in g.edges(data=True):

d['weight'] = c[u, v]*minLineWidth

edges,weights = zip(*nx.get_edge_attributes(g,'weight').items())

and using width=[d['weight'] for u,v, d in g.edges(data=True)] in nx.draw_networkx_edges() as provided in the solution below.

Additionally, I was able to scale color using the following:

# Set Edge Color based on weight

values = range(7958) #this is based on the number of edges in the graph, use print len(g.edges()) to determine this

jet = cm = plt.get_cmap('YlOrRd')

cNorm = colors.Normalize(vmin=0, vmax=values[-1])

scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

colorList = []

for i in range(7958):

colorVal = scalarMap.to_rgba(values[i])

colorList.append(colorVal)

And then using the argument edge_color=colorList in nx.draw_networkx_edges().

解决方案

Try this on for size.

Note: I added a duplicate of an existing edge, just to show the behavior when there are repeats in your multigraph.

from collections import Counter

c = Counter(g.edges()) # Contains frequencies of each directed edge.

for u, v, d in g.edges(data=True):

d['weight'] = c[u, v]

print(list(g.edges(data=True)))

#[(340, 269, {'weight': 1}),

# (340, 340, {'weight': 1}),

# (269, 340, {'weight': 1}),

# (398, 279, {'weight': 1}),

# (69, 28, {'weight': 1}),

# (382, 27, {'weight': 1}),

# (27, 285, {'weight': 2}),

# (27, 285, {'weight': 2}),

# (120, 422, {'weight': 1}),

# (422, 217, {'weight': 1}),

# (217, 340, {'weight': 1}),

# (458, 442, {'weight': 1}),

# (291, 431, {'weight': 1}),

# (68, 27, {'weight': 1}),

# (112, 269, {'weight': 1})]

Edit: To visualize the graph with edge weights as thicknesses, use this:

nx.draw_networkx(g, width=[d['weight'] for _, _, d in g.edges(data=True)])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用PythonNetworkX库来实现根据图的权重画拓扑图的功能。下面是一个简单的示例代码: ```python import networkx as nx import matplotlib.pyplot as plt # 创建图 G = nx.Graph() # 添加节点 G.add_nodes_from(['A', 'B', 'C', 'D']) # 添加边和权重 G.add_edge('A', 'B', weight=2) G.add_edge('A', 'C', weight=3) G.add_edge('B', 'C', weight=1) G.add_edge('B', 'D', weight=4) G.add_edge('C', 'D', weight=5) # 获取边的权重 edge_weights = nx.get_edge_attributes(G, 'weight') # 设置边的粗细 edge_widths = [0.1 * G[u][v]['weight'] for u, v in G.edges()] # 绘制图形 pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=500) nx.draw_networkx_edges(G, pos, width=edge_widths, edge_color='gray') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_weights, font_color='red') nx.draw_networkx_labels(G, pos, font_size=16, font_family='sans-serif') # 显示图形 plt.axis('off') plt.show() ``` 在上面的代码中,我们首先创建了一个包含4个节点的图,并添加了5条带权重的边。然后,我们使用`nx.get_edge_attributes`函数获取每条边的权重,并将其存储在`edge_weights`字典中。接着,我们计算每条边的粗细,将其存储在`edge_widths`列表中。最后,我们使用`nx.draw_networkx_nodes`和`nx.draw_networkx_edges`函数绘制图形,并使用`nx.draw_networkx_edge_labels`和`nx.draw_networkx_labels`函数添加标签。 运行上面的代码,你会得到一个带权重的拓扑图,其中边的粗细代表了它们的权重大小。你可以根据需要修改节点的颜色、边的颜色和样式等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值