绘制 MultiDiGraph 的边和标签#

本例展示了如何绘制 MultiDiGraph 类对象的边和标签。这也适用于 DiGraph 和 MultiGraph 类对象。

创建了 4 个图,每个图在 2 个节点之间具有不同数量的边。最终的图包含每对节点间的 4 条边以及每个节点的 2 个自环。

MultiGraph 可以有无限多的多重边,这些边可以用不同的角度绘制,并且理论上节点标签可以保持可见。

多重自环可以在节点的 4 个方向绘制。随后的环将导致重叠。

Product x 1, Product x 2, Product x 3, Product x 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):
    """
    Length of connectionstyle must be at least that of a maximum number of edges
    between pair of nodes. This number is maximum one-sided connections
    for directed graph and maximum total connections for undirected graph.
    """
    # Works with arc3 and angle3 connectionstyles
    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()

脚本总运行时间: (0 分钟 0.912 秒)

图库由 Sphinx-Gallery 生成