Note
Go to the end to download the full example code.
绘制多重有向图的边和标签#
本示例展示了如何绘制MultiDiGraph类对象的边和标签。 同样适用于DiGraph和MultiGraph类对象。
创建了4个图,每个图在2个节点之间具有不同数量的边。 最终的图在每对节点中包含4条边,每个节点有2个自环。
MultiGraph可以有无限多的多重边,这些边可以用不同的角度绘制,理论上节点标签可以保持可见。
多重自环可以在节点的4个方向上绘制。 后续的环将导致重叠。
import itertools as it
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
def draw_labeled_multigraph(G, attr_name, ax=None):
"""连接样式长度必须至少为一对节点之间最大边数。对于有向图,此数字为单向连接的最大值;对于无向图,则为总连接的最大值。
"""
# 适用于arc3和angle3连接样式
connectionstyle = [f"arc3,rad={r}" for r in it.accumulate([0.15] * 4)]
# connectionstyle = [f"angle3,angleA={r}" for r in it.accumulate([30] * 4)]
pos = nx.shell_layout(G)
nx.draw_networkx_nodes(G, pos, ax=ax)
nx.draw_networkx_labels(G, pos, font_size=20, ax=ax)
nx.draw_networkx_edges(
G, pos, edge_color="grey", connectionstyle=connectionstyle, ax=ax
)
labels = {
tuple(edge): f"{attr_name}={attrs[attr_name]}"
for *edge, attrs in G.edges(keys=True, data=True)
}
nx.draw_networkx_edge_labels(
G,
pos,
labels,
connectionstyle=connectionstyle,
label_pos=0.3,
font_color="blue",
bbox={"alpha": 0},
ax=ax,
)
nodes = "ABC"
prod = list(it.product(nodes, repeat=2))
pair_dict = {f"Product x {i}": prod * i for i in range(1, 5)}
fig, axes = plt.subplots(2, 2)
for (name, pairs), ax in zip(pair_dict.items(), np.ravel(axes)):
G = nx.MultiDiGraph()
for i, (u, v) in enumerate(pairs):
G.add_edge(u, v, w=round(i / 3, 2))
draw_labeled_multigraph(G, "w", ax)
ax.set_title(name)
fig.tight_layout()
plt.show()
Total running time of the script: (0 minutes 0.353 seconds)