Defining graphs: directed, undirected, and weighted graphs

Environment

Python 3.14.6, NumPy 2.4.6, NetworkX 3.7, Matplotlib 3.11.2 (Jupyter Notebook).

This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.

Book: Graph Theory and Practice
Chapter: Graph basics and matrix representations

Overview

A graph represents objects as vertices and their relationships as edges. Stations and railway lines, relationships between people, and links between web pages can all use this format. Here, “graph” means a network, rather than a bar chart or line chart.

This article defines undirected, directed, and weighted graphs and compares them using the same five vertices. We draw graphs from edge lists and calculate degrees and adjacency matrices in Python. The basic examples are finite graphs without self-loops or parallel edges.

Setup

Run the cells in order. Round values to three significant figures only for display.

Check the environment, import libraries, and configure plots
import platform
import sys
from importlib.metadata import version
from pathlib import Path
from pprint import pprint

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from IPython.display import Latex, SVG, display
from matplotlib import font_manager
from matplotlib.ticker import MaxNLocator

assert sys.version_info[:3] == (3, 14, 6), "Python 3.14.6を選択する"
print("実行環境: wa-src(3.14.6)")
print(f"Python: {platform.python_version()}")
for package in ("numpy", "networkx", "matplotlib", "IPython"):
    print(f"{package}: {version(package)}")

OUT = Path("101_nb_files")
OUT.mkdir(exist_ok=True)

# 日本語フォントを選び、SVGでは文字をパスとして保存する。
available_fonts = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ("Hiragino Sans", "Noto Sans CJK JP", "IPAexGothic", "Yu Gothic"):
    if candidate in available_fonts:
        plt.rcParams["font.family"] = candidate
        break
plt.rcParams.update({"font.size": 11, "svg.fonttype": "path"})


def sig3(value):
    """小数を末尾のゼロも含めて有効数字3桁で表示する。"""
    return "0" if value == 0 else f"{float(value):#.3g}"


np.set_printoptions(formatter={"float_kind": sig3})


def save_svg(fig, name):
    """保存したSVGをそのままノートブックにも表示する。"""
    path = OUT / f"{name}.svg"
    fig.savefig(path, format="svg", bbox_inches="tight")
    display(SVG(filename=str(path)))
    plt.close(fig)
実行環境: wa-src(3.14.6)
Python: 3.14.6
numpy: 2.4.6
networkx: 3.7
matplotlib: 3.11.2
IPython: 9.18.1

1. Define a graph using vertices and edges

Let $V$ be the vertex set and $E$ the edge set. A graph is the following pair. The notation $|S|$ denotes the number of elements in $S$.

$$ G=(V,E),\qquad n=|V|,\qquad m=|E|. $$

An undirected edge is an unordered pair of vertices. An undirected graph without self-loops or parallel edges is called a simple graph. In this case,

$$ E\subseteq\{\{u,v\}\mid u,v\in V,\ u\ne v\}. $$

Define a concrete example as follows.

$$ \begin{aligned} V&=\{A,B,C,D,E\},\\ E&=\{\{A,B\},\{A,C\},\{B,C\},\{C,D\}\},\\ n&=5,\qquad m=4. \end{aligned} $$

The set $E$ and the vertex named $E$ are different objects. Vertex $E$ has no edges and is called an isolated vertex. Adding only the edges would omit isolated vertices, so the code first adds every vertex.

NetworkX’s Graph represents an undirected graph. NetworkX documentation: graph types

nodes = ["A", "B", "C", "D", "E"]
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]
G = nx.Graph()
G.add_nodes_from(nodes)  # 孤立頂点Eも残す。
G.add_edges_from(edges)

print("頂点の一覧:")
pprint(list(G.nodes))
print("辺の一覧(無向辺のタプルの順序には意味がない):")
pprint(list(G.edges))
display(Latex(r"\(n=" + str(G.number_of_nodes())
              + r",\quad m=" + str(G.number_of_edges()) + r"\)"))

pos = {"A": (0, 1), "B": (0, -1), "C": (2, 0),
       "D": (4, 0), "E": (4, 1)}


def draw_graph(graph, ax, title, positions=None, weighted=False):
    """頂点配置と描画方法をそろえて、グラフの違いを比較する。"""
    positions = pos if positions is None else positions
    curve = "arc3,rad=0.300" if graph.is_directed() else "arc3"
    arrow_options = {"arrowsize": 20} if graph.is_directed() else {}
    nx.draw_networkx(
        graph, pos=positions, ax=ax, node_color="#c8e1f1", node_size=650,
        edge_color="#465968", width=2, arrows=graph.is_directed(),
        connectionstyle=curve, font_family="DejaVu Sans", **arrow_options,
    )
    if weighted:
        labels = {(u, v): sig3(data["weight"])
                  for u, v, data in graph.edges(data=True)}
        label_artists = nx.draw_networkx_edge_labels(
            graph, positions, labels, ax=ax, font_size=10,
            connectionstyle=curve, rotate=False,
        )
        for label in label_artists.values():
            label.set_zorder(3)  # 経路を重ねても重みを読めるようにする。
    ax.set_title(title)
    ax.margins(0.250)
    ax.set_axis_off()


fig, axes = plt.subplots(1, 2, figsize=(10, 3.60), layout="constrained")
draw_graph(G, axes[0], "固定した配置")
draw_graph(G, axes[1], "円周上の配置", positions=nx.circular_layout(G))
save_svg(fig, "01_undirected_layouts")
頂点の一覧:
['A', 'B', 'C', 'D', 'E']
辺の一覧(無向辺のタプルの順序には意味がない):
[('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')]

$$ n=5,\quad m=4 $$

The two drawings in Figure 1 represent the same graph. Vertex coordinates and line lengths are not part of $G=(V,E)$ as defined here. Crossing lines do not create a connection unless a vertex is explicitly placed at the intersection. Checking the edge list before the drawing helps avoid misreading the connections.

2. Degrees in an undirected graph

When the edge $\{u,v\}$ exists, $u$ and $v$ are adjacent. The number of edges incident to vertex $v$ is its degree, $d(v)$. In this example without self-loops or parallel edges, it equals the number of neighboring vertices.

$$ d(A)=2,\quad d(B)=2,\quad d(C)=3,\quad d(D)=1,\quad d(E)=0. $$

Each undirected edge contributes one to the degree at each endpoint. Summing all vertex degrees therefore counts every edge twice.

$$ \sum_{v\in V}d(v)=2|E|. $$

This is the handshaking lemma. In our example,

$$ \sum_{v\in V}d(v)=2+2+3+1+0=8=2\times4. $$

The average degree is the sum of the degrees divided by the number of vertices.

$$ \bar d=\frac{1}{n}\sum_{v\in V}d(v)=\frac{2m}{n} =\frac{2\times4}{5}=1.60. $$

degrees = dict(G.degree())
pprint(degrees)
assert sum(degrees.values()) == 2 * G.number_of_edges()
mean_degree = sum(degrees.values()) / G.number_of_nodes()
display(Latex(r"\(\bar d=\frac{8}{5}=" + sig3(mean_degree) + r"\)"))

fig, ax = plt.subplots(figsize=(6, 3.20), layout="constrained")
bars = ax.bar(nodes, [degrees[v] for v in nodes], color="#6a9fbc")
ax.bar_label(bars, padding=3)
ax.set(xlabel="頂点", ylabel="次数", title="各頂点に接続する辺の本数", ylim=(0, 4))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
save_svg(fig, "02_degrees")
{'A': 2, 'B': 2, 'C': 3, 'D': 1, 'E': 0}

$$ \bar d=\frac{8}{5}=1.60 $$

In Figure 2, vertex $C$ has the largest degree, 3, and isolated vertex $E$ has degree 0.

3. Directed edges have an order

A directed edge is an ordered pair $(u,v)$ indicating a direction from $u$ to $v$. For an undirected edge, $\{u,v\}=\{v,u\}$, whereas for directed edges, $u\ne v$ implies $(u,v)\ne(v,u)$. Denote the set of directed edges in this example by $E_{\mathrm{dir}}$.

$$ \begin{aligned} G_{\mathrm{dir}}&=(V,E_{\mathrm{dir}}),\\ E_{\mathrm{dir}}&=\{(A,B),(B,A),(A,C),(B,C),(C,D)\}. \end{aligned} $$

We count $A\to B$ and $B\to A$ as separate edges; they are not parallel edges in the same direction. This distinction matters for web links and one-way roads.

The number of outgoing edges is the out-degree $d^{\mathrm{out}}(v)$, and the number of incoming edges is the in-degree $d^{\mathrm{in}}(v)$. Each edge has exactly one source and one target, so

$$ \sum_{v\in V}d^{\mathrm{out}}(v) =\sum_{v\in V}d^{\mathrm{in}}(v) =|E_{\mathrm{dir}}|. $$

Here the total out-degree is $2+2+1+0+0=5$ and the total in-degree is $1+1+2+1+0=5$. Although $D$ has out-degree 0, it has in-degree 1 and is therefore not isolated.

D = nx.DiGraph()
D.add_nodes_from(nodes)
D.add_edges_from([("A", "B"), ("B", "A"), ("A", "C"),
                  ("B", "C"), ("C", "D")])
out_degree = dict(D.out_degree())
in_degree = dict(D.in_degree())
print("出次数:")
pprint(out_degree)
print("入次数:")
pprint(in_degree)
assert sum(out_degree.values()) == sum(in_degree.values()) == 5
print(f"AからDへ到達できる: {nx.has_path(D, 'A', 'D')}")
print(f"DからAへ到達できる: {nx.has_path(D, 'D', 'A')}")

fig, axes = plt.subplots(1, 2, figsize=(10, 3.60), layout="constrained")
draw_graph(D, axes[0], "有向グラフ:矢印の向きを区別する")
x = np.arange(len(nodes))
axes[1].bar(x - 0.180, [out_degree[v] for v in nodes],
            width=0.360, label="出次数", color="#4f91b4")
axes[1].bar(x + 0.180, [in_degree[v] for v in nodes],
            width=0.360, label="入次数", color="#d99851")
axes[1].set(xticks=x, xticklabels=nodes, ylabel="辺の本数", ylim=(0, 3),
            title="出次数と入次数")
axes[1].yaxis.set_major_locator(MaxNLocator(integer=True))
axes[1].legend()
save_svg(fig, "03_directed_degrees")
出次数:
{'A': 2, 'B': 2, 'C': 1, 'D': 0, 'E': 0}
入次数:
{'A': 1, 'B': 1, 'C': 2, 'D': 1, 'E': 0}
AからDへ到達できる: True
DからAへ到達できる: False

In Figure 3, from $A$ we can go through $C$ to $D$. In contrast, $D$ has no outgoing arrows, so there is no route from $D$ back to $A$.

4. Weighted graphs assign numbers to edges

A weighted graph includes a function $w$ assigning a number to each edge.

$$ G_w=(V,E,w),\qquad w:E\to\mathbb{R}. $$

The meaning of a weight depends on the problem: distance or travel time for roads, or capacity for communication links, for example. Zero and negative weights can be defined in general, but here weights are positive travel times in minutes.

Undirected edgeTravel time (minutes)
$\{A,B\}$$1.50$
$\{A,C\}$$4.00$
$\{B,C\}$$0.750$
$\{C,D\}$$2.00$

Edge direction and the presence of weights are separate classifications. Both Graph and DiGraph can store a weight attribute. In the directed version in Figure 4, only the reverse edge $B\to A$ has a different travel time of $2.50$ minutes.

DirectionUnweightedWeighted
UndirectedWhether a mutual connection existsSame travel time in both directions
DirectedWhether a one-way connection existsTravel time for each direction

A larger weight does not necessarily mean a stronger relationship. For travel times, a larger value means a longer journey. Always check what the numbers mean and which units they use.

weighted_edges = [("A", "B", 1.50), ("A", "C", 4.00),
                  ("B", "C", 0.750), ("C", "D", 2.00)]
W = nx.Graph()
W.add_nodes_from(nodes)
W.add_weighted_edges_from(weighted_edges)

WD = nx.DiGraph()
WD.add_nodes_from(nodes)
WD.add_weighted_edges_from(weighted_edges + [("B", "A", 2.50)])

# 辞書の小数は表示時だけ文字列にして、末尾のゼロも残す。
pprint({f"{u}-{v}": sig3(data["weight"])
        for u, v, data in W.edges(data=True)})

fig, axes = plt.subplots(1, 2, figsize=(10, 3.60), layout="constrained")
draw_graph(W, axes[0], "無向・重み付き(分)", weighted=True)
draw_graph(WD, axes[1], "有向・重み付き(分)", weighted=True)
save_svg(fig, "04_weighted_graphs")
{'A-B': '1.50', 'A-C': '4.00', 'B-C': '0.750', 'C-D': '2.00'}

Distinguish edge count from travel time

Here, a path is a sequence of adjacent vertices with no repeated vertex. A path $P=(v_0,\ldots,v_k)$ has $k$ edges, and its travel time is the sum of their weights.

$$ T(P)=\sum_{i=0}^{k-1}w(\{v_i,v_{i+1}\}). $$

Compare paths from $A$ to $D$ in the undirected example.

$$ \begin{aligned} T(A,C,D) &=w(\{A,C\})+w(\{C,D\})\\ &=4.00+2.00=6.00,\\ T(A,B,C,D) &=w(\{A,B\})+w(\{B,C\})+w(\{C,D\})\\ &=1.50+0.750+2.00=4.25. \end{aligned} $$

The first path has two edges and the second has three. The path with fewer edges is not the path with the shorter travel time. These are the only two paths from $A$ to $D$ in this example. Below, weight=None minimizes the edge count and weight="weight" minimizes travel time. NetworkX documentation: shortest_path

routes = {
    "辺数が最小": nx.shortest_path(W, "A", "D", weight=None),
    "所要時間が最小": nx.shortest_path(W, "A", "D", weight="weight"),
}
fig, axes = plt.subplots(1, 2, figsize=(10, 3.60), layout="constrained")
for ax, (label, route) in zip(axes, routes.items()):
    route_edges = list(zip(route[:-1], route[1:]))
    total = sum(W[u][v]["weight"] for u, v in route_edges)
    pprint({"基準": label, "経路": route, "辺数": len(route_edges),
            "所要時間(分)": sig3(total)})
    draw_graph(W, ax, f"{label}:{len(route_edges)}辺、{sig3(total)}分", weighted=True)
    # 選ばれた経路を太い線で重ねる。ラベルより奥に表示される。
    nx.draw_networkx_edges(W, pos, edgelist=route_edges, ax=ax,
                           edge_color="#c56630", width=4)
save_svg(fig, "05_paths")
{'基準': '辺数が最小', '所要時間(分)': '6.00', '経路': ['A', 'C', 'D'], '辺数': 2}
{'基準': '所要時間が最小', '所要時間(分)': '4.25', '経路': ['A', 'B', 'C', 'D'], '辺数': 3}

5. Represent connections with an adjacency matrix

Fix the vertex order as $(A,B,C,D,E)$. In the adjacency matrix $\mathbf{A}=(a_{ij})$, rows indicate sources and columns indicate targets. Define the entries as follows. An undirected edge puts a 1 in both directions.

$$ a_{ij}=\begin{cases} 1 & \text{if }v_i\to v_j\text{ is an edge},\\ 0 & \text{otherwise}. \end{cases} $$

The undirected graph has the following matrix.

$$ \mathbf{A}=\begin{bmatrix} 0&1&1&0&0\\ 1&0&1&0&0\\ 1&1&0&1&0\\ 0&0&1&0&0\\ 0&0&0&0&0 \end{bmatrix}. $$

Symmetric positions have equal values, such as $a_{AC}=a_{CA}=1$, so $\mathbf{A}^{\mathsf T}=\mathbf{A}$. The diagonal entries are 0 because there are no self-loops. The row and column for isolated vertex $E$ are all 0.

In the directed graph, $C\to D$ exists but $D\to C$ does not, giving $a^{\mathrm{dir}}_{CD}=1$ and $a^{\mathrm{dir}}_{DC}=0$. An adjacency matrix is generally not symmetric for a directed graph. It is symmetric when every edge has its reverse edge.

A weighted adjacency matrix $\mathbf{W}$ places each edge’s weight in the corresponding entry. All weights are positive here, so 0 can represent the absence of an edge.

Specify the vertex order with nodelist=nodes. Use weight=None to extract connections and weight="weight" to extract weights. NetworkX documentation: to_numpy_array

A = nx.to_numpy_array(G, nodelist=nodes, weight=None, dtype=int)
A_dir = nx.to_numpy_array(D, nodelist=nodes, weight=None, dtype=int)
W_matrix = nx.to_numpy_array(W, nodelist=nodes, weight="weight")


def show_matrix(symbol, matrix):
    """配列はpprintで、数式はLaTeXの出力欄で表示する。"""
    pprint(matrix)
    integer = np.issubdtype(matrix.dtype, np.integer)
    rows = [" & ".join(str(int(x)) if integer else sig3(x) for x in row)
            for row in matrix]
    body = r" \\\\ ".join(rows)
    display(Latex(r"\(" + symbol + r"=\begin{bmatrix}"
                  + body + r"\end{bmatrix}\)"))


show_matrix(r"\mathbf{A}", A)
show_matrix(r"\mathbf{A}_{\mathrm{dir}}", A_dir)
show_matrix(r"\mathbf{W}", W_matrix)
assert np.array_equal(A, A.T)
assert not np.array_equal(A_dir, A_dir.T)

fig, axes = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
for ax, matrix, title in zip(
    axes, (A, A_dir, W_matrix), ("無向:接続の有無", "有向:行から列へ", "無向:所要時間(分)")
):
    # 各マスをベクトル図形として描き、SVGを拡大しても鮮明に保つ。
    grid = np.arange(len(nodes) + 1) - 0.500
    ax.pcolormesh(grid, grid, matrix, cmap="Blues", vmin=0, vmax=matrix.max(),
                  edgecolors="#dbe1e6", linewidth=0.500)
    ax.set_aspect("equal")
    ax.set_ylim(4.50, -0.500)  # 行列と同じく、第1行を上にする。
    for i, j in np.ndindex(matrix.shape):
        value = matrix[i, j]
        label = sig3(value) if matrix is W_matrix else str(int(value))
        ax.text(j, i, label, ha="center", va="center", fontsize=10,
                color="white" if value > matrix.max() / 2 else "black")
    ax.set(xticks=range(5), xticklabels=nodes, yticks=range(5), yticklabels=nodes,
           xlabel="到着点(列)", ylabel="出発点(行)", title=title)
save_svg(fig, "06_adjacency_matrices")
array([[0, 1, 1, 0, 0],
       [1, 0, 1, 0, 0],
       [1, 1, 0, 1, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0]])

$$ \mathbf{A}=\begin{bmatrix}0 & 1 & 1 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 \\ 1 & 1 & 0 & 1 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ array([[0, 1, 1, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

$$ \mathbf{A}_{\mathrm{dir}}=\begin{bmatrix}0 & 1 & 1 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ array([[0, 1.50, 4.00, 0, 0], [1.50, 0, 0.750, 0, 0], [4.00, 0.750, 0, 2.00, 0], [0, 0, 2.00, 0, 0], [0, 0, 0, 0, 0]])

$$ \mathbf{W}=\begin{bmatrix}0 & 1.50 & 4.00 & 0 & 0 \\ 1.50 & 0 & 0.750 & 0 & 0 \\ 4.00 & 0.750 & 0 & 2.00 & 0 \\ 0 & 0 & 2.00 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$

Figure 6 shows the matrix entries using colors as well as numbers. The left matrix is symmetric, the middle one is asymmetric, and the right one contains weights. The color scales differ, so compare the printed numbers when comparing values across panels.

Check degrees using row and column sums

Let $\mathbf{1}$ be the all-ones column vector. For an undirected graph without self-loops, the degree vector is $\mathbf{d}=\mathbf{A}\mathbf{1}$, the vector of row sums.

$$ \mathbf{d}=\begin{bmatrix} 0+1+1+0+0\\1+0+1+0+0\\1+1+0+1+0\\0+0+1+0+0\\0+0+0+0+0 \end{bmatrix} =\begin{bmatrix}2\\2\\3\\1\\0\end{bmatrix}. $$

In a directed graph, row sums give out-degrees and column sums give in-degrees.

$$ \mathbf{d}^{\mathrm{out}}=\mathbf{A}_{\mathrm{dir}}\mathbf{1},\qquad \mathbf{d}^{\mathrm{in}}=\mathbf{A}_{\mathrm{dir}}^{\mathsf T}\mathbf{1}. $$

The row sum $\mathbf{s}=\mathbf{W}\mathbf{1}$ of a weighted matrix gives the sum of incident edge weights, rather than their count. This is the weighted degree, also called strength. For example, at $A$,

$$ d(A)=2,\qquad s(A)=1.50+4.00=5.50. $$

Since our weights are travel times, $s(A)$ is simply their sum over incident edges. It does not by itself measure how convenient the station is. NetworkX calculates it with degree(weight="weight"). NetworkX documentation: Graph.degree

print("無向グラフの次数(行の和):")
pprint(A.sum(axis=1))
print("有向グラフの出次数(行の和):")
pprint(A_dir.sum(axis=1))
print("有向グラフの入次数(列の和):")
pprint(A_dir.sum(axis=0))
print("重み付き次数:")
strength = W_matrix.sum(axis=1)
pprint(strength)

# 辺から数えた値と、行列から計算した値を照合する。
assert np.array_equal(A.sum(axis=1), [degrees[v] for v in nodes])
assert np.array_equal(A_dir.sum(axis=1), [out_degree[v] for v in nodes])
assert np.array_equal(A_dir.sum(axis=0), [in_degree[v] for v in nodes])
assert np.allclose(strength, [W.degree(v, weight="weight") for v in nodes])
無向グラフの次数(行の和):
array([2, 2, 3, 1, 0])
有向グラフの出次数(行の和):
array([2, 2, 1, 0, 0])
有向グラフの入次数(列の和):
array([1, 1, 2, 1, 0])
重み付き次数:
array([5.50, 2.25, 6.75, 2.00, 0])

6. Self-loops, parallel edges, and zero weights

A self-loop has the same source and target vertex. In an undirected graph, one self-loop contributes twice to the degree. Multiple edges joining the same pair of vertices are called parallel edges. They can represent separate railway lines between the same two stations, for example.

NetworkX’s Graph and DiGraph allow self-loops but do not retain parallel edges. Adding an existing edge updates its attributes. Use MultiGraph or MultiDiGraph to distinguish parallel edges. NetworkX documentation: graph types

loop_graph = nx.Graph()
loop_graph.add_edge("A", "A")
multi_graph = nx.MultiGraph()
multi_graph.add_edge("A", "B")
multi_graph.add_edge("A", "B")

print(f"自己ループ1本の次数: {loop_graph.degree('A')}")
print(f"多重辺の本数: {multi_graph.number_of_edges()}")
pprint(list(multi_graph.edges(keys=True)))

fig, axes = plt.subplots(1, 2, figsize=(8, 3.40), layout="constrained")
nx.draw_networkx(loop_graph, pos={"A": (0, 0)}, ax=axes[0],
                 node_color="#c8e1f1", node_size=650)
axes[0].set(xlim=(-1, 1), ylim=(-1, 1), title="自己ループ:1辺、次数2")

# 2本の辺を異なる曲率で描いて、重なりを避ける。
nx.draw_networkx(multi_graph, pos={"A": (0, 0), "B": (1, 0)}, ax=axes[1],
                 node_color="#c8e1f1", node_size=650, arrows=True,
                 arrowstyle="-", connectionstyle=["arc3,rad=0.250", "arc3,rad=-0.250"])
axes[1].set(xlim=(-0.500, 1.50), ylim=(-0.600, 0.600), title="多重辺:AとBの間に2辺")
for ax in axes:
    ax.set_axis_off()
save_svg(fig, "07_loops_parallel_edges")
自己ループ1本の次数: 2
多重辺の本数: 2
[('A', 'B', 0), ('A', 'B', 1)]

For the self-loop in Figure 7, NetworkX places 1 on the adjacency matrix diagonal, while the degree is 2. Thus the row-sum identity in Section 5 cannot be used unchanged. Check how self-loops are counted in the matrix definition you use.

If zero-weight edges are allowed, a zero in the weighted matrix cannot distinguish an absent edge from an edge of weight 0. Keep a separate connection matrix, or represent nonedges by np.nan, as below. NetworkX documentation: to_numpy_array

zero_graph = nx.Graph()
zero_graph.add_nodes_from(["A", "B", "C"])
zero_graph.add_edge("A", "B", weight=0)
zero_matrix = nx.to_numpy_array(
    zero_graph, nodelist=["A", "B", "C"], weight="weight", nonedge=np.nan
)
print("重み0の辺は0、辺がない成分はnan:")
pprint(zero_matrix)
assert zero_matrix[0, 1] == 0
assert np.isnan(zero_matrix[0, 2])
重み0の辺は0、辺がない成分はnan:
array([[nan, 0, nan],
       [0, nan, nan],
       [nan, nan, nan]])

Conclusion

We defined graphs using vertex and edge sets, then compared undirected, directed, and weighted graphs through drawings, degrees, and adjacency matrices.

Undirected edges do not distinguish endpoint order; directed edges distinguish source and target. Either kind can carry weights, whose meanings and units must be specified. A path with the fewest edges need not have the smallest total weight.

Fix the vertex order and the meanings of rows and columns when using adjacency matrices. For self-loops, parallel edges, or zero weights, also check the edge-counting conventions and matrix definitions.

References are the NetworkX documentation cited above: graph types , to_numpy_array , Graph.degree , and shortest_path .