[英]How to show number of connections as edge label and weight based on number of connections
如何根据连接数将连接数显示为边缘标签和边缘权重。
到目前为止,我的代码:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.DiGraph()
G.add_edge('a','b');
G.add_edge('c','d');
G.add_edge('c','a');
G.add_edge('a','b');
G.add_edge('b','a');
nx.draw(G,with_labels=True)
plt.show()
我的目标是基于大量数据创建图(Python脚本)
网络和matplotlib的新手
您遇到的基本问题是networkx
并不真正适合于绘制加权的有向图。 可以做到的,但是不是很漂亮。 特别是,没有真正的支持绘制双向连接,因为双向连接是相互绘制的。 下面,我尝试通过在连接的头部附近绘制边缘权重来解决该问题,但这并不是很好。
import matplotlib.pyplot as plt
import networkx as nx
G=nx.MultiDiGraph()
G.add_edge('a','b');
G.add_edge('c','d');
G.add_edge('c','a');
G.add_edge('a','b');
G.add_edge('b','a');
edge_to_count = dict()
for edge in G.edges():
try:
edge_to_count[edge] += 1
except KeyError:
edge_to_count[edge] = 1
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_to_count, label_pos=0.25)
plt.show()
如果要将多边缘表示为边缘权重,则代码将更改为:
import matplotlib.pyplot as plt
import networkx as nx
# get edge weights based on edge count
edges = [('a','b'),
('c','d'),
('c','a'),
('a','b'),
('b','a')]
edge_to_count = dict()
for edge in edges:
try:
edge_to_count[edge] += 1.
except KeyError:
edge_to_count[edge] = 1.
# convert to networkx edge list format
edges = [(k[0], k[1], dict(weight=v)) for k, v in edge_to_count.items()]
# create graph
G = nx.DiGraph()
G.add_edges_from(edges)
# precompute layout to be used by both, draw() and draw_networkx_edge_labels
pos = nx.spring_layout(G)
# draw graph first, then labels on top
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_to_count, label_pos=0.25)
plt.show()
在某个时候,我花了一段时间解决这个确切的问题,所以我写了一个自己的小网络绘图库,称为netgraph
(可通过pip和github获得 )。 该API与networkx非常相似,除了我摆脱了一些我可能会为了向后兼容而保留在networkx中的命名不一致之处。 默认输出如下所示:
如您所见,它支持绘制双向/平行边。 默认情况下,边缘根据其重量着色。 由于它接受networkx图形对象作为输入,因此与networkx集成非常容易(它也支持多种输入格式)。
import matplotlib.pyplot as plt
import networkx
import netgraph
# get edge weights based on edge count
edges = [('a','b'),
('c','d'),
('c','a'),
('a','b'),
('b','a')]
edge_to_count = dict()
for edge in edges:
try:
edge_to_count[edge] += 1.
except KeyError:
edge_to_count[edge] = 1.
# convert to networkx edge list format
edges = [(k[0], k[1], dict(weight=v)) for k, v in edge_to_count.items()]
# create graph
G = nx.DiGraph()
G.add_edges_from(edges)
# draw
netgraph.draw(G, edge_labels=edge_to_count, edge_label_font_size=8)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.