简体   繁体   English

使用边缘元数据绘制有向图(使用 Python 中的 NetworkX)

[英]Drawing Directed Graph with Edge meta-data (with NetworkX in Python)

I have a directed multigraph that I want to represent as a (complete) directed graph with edge meta-data such that if there are e number of edges from node A to node B (in the original multigraph) then I save e as the meta-data for the edge (A,B) in the new (not-multi) directed graph.我有一个有向多图,我想将其表示为带有边元数据的(完整)有向图,这样如果从节点 A 到节点 B(在原始多图中)有 e 个边,那么我将 e 保存为元数据-新(非多)有向图中边(A,B)的数据。

I can construct the graph as follows:我可以按如下方式构建图表:

DG = nx.complete_graph(node_list, create_using= nx.DiGraph() )

where node_list = ['node_A', 'node_B', ....]其中 node_list = ['node_A', 'node_B', ....]

I can add the edges using:我可以使用以下方法添加边缘:

DG.edges[('node_A', 'node_B')]['edge_count'] = 1

But how do I print this value (nicely) using the draw command?但是我如何使用 draw 命令(很好地)打印这个值呢? I tried the following我尝试了以下

nx.draw(DG, with_labels = True)
plt.show()

But the edge values hide;但是边缘值隐藏了; what's more, I would need a nice way to show the meta-data associated with edge (A,B) and easily distinguishing it from edge (B,A).更重要的是,我需要一种很好的方式来显示与边 (A,B) 关联的元数据,并轻松地将它与边 (B,A) 区分开来。

You should be able to do the following:您应该能够执行以下操作:

edge_labels = nx.get_edge_attributes(G,'edge_count')

pos = nx.spring_layout(G)
nx.draw(G, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = edge_labels)
plt.show()

Here's an approach that uses curved arrows to avoid overlapping labels这是一种使用弯曲箭头来避免标签重叠的方法

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from(range(4))

G.add_edge(0,1,edge_count = 1)
G.add_edge(1,0,edge_count = 2)
G.add_edge(1,2,edge_count = 2)
G.add_edge(2,3,edge_count = 3)
G.add_edge(3,0,edge_count = 2)

def offset(d, pos, dist = .1):
    for (u,v),obj in d.items():
        par = dist*(pos[v] - pos[u])
        dx,dy = par[1],-par[0]
        x,y = obj.get_position()
        obj.set_position((x+dx,y+dy))

edge_labels = nx.get_edge_attributes(G,'edge_count')
pos = nx.spring_layout(G)
nx.draw(G, pos = pos, with_labels=True, connectionstyle = 'arc3,rad=0.2', node_color = 'orange')
d = nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = edge_labels)
offset(d,pos)
plt.gca().set_aspect('equal')
plt.show()

Result from the above:上述结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM