仅绘制 Osmnx 网络的强连接组件

Plot only the strongly connected components of a Osmnx network

我有以下网络:

import osmnx as ox
import igraph as ig
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx
import numpy as np
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')
G_nx = nx.relabel.convert_node_labels_to_integers(G)
G_1 = [c for c in nx.strongly_connected_components(G)]

如何绘制我的新 G_1 网络?

请注意,您的示例中的 G_1 是一组连通分量的列表。您需要生成诱导子图才能绘制它们。 假设我们有图表:

具有强连通分量:

list(nx.strongly_connected_components(G))
# [{3, 8, 9}, {1, 2, 4, 5}, {6, 7}]

您可以使用 nx.subgraph 从连通分量生成导出子图,并从那里绘制生成的图。在这里,我使用子图在网格中可视化它们:

from itertools import zip_longest
from matplotlib import pyplot as plt
from math import ceil

comps = list(nx.strongly_connected_components(G))
n_cols = 2

fig, axes = plt.subplots(nrows=int(ceil(len(comps)/n_cols)), 
                         ncols=n_cols, 
                         figsize=(15,8))

for comp, ax in zip_longest(comps, axes.flatten()):
    if comp is None:
        plt.box(False)
        plt.axis('off')
        continue
    G_sub = G.subgraph(comp)
    nx.draw(G_sub, with_labels=True, node_color='lightblue', node_size=500, ax=ax)

您可以通过使用 get_largest_component or the induce_subgraph 函数在 OSMnx 中执行此操作,具体取决于您的最终目标。我在这里提供两种选择:

import networkx as nx
import osmnx as ox
ox.config(log_console=True, use_cache=True)
city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')
print(len(G)) #9699

# OPTION 1: if you only want the largest strongly connected component
Gc = ox.utils_graph.get_largest_component(G, strongly=True)
print(len(Gc)) #9503
fig, ax = ox.plot_graph(Gc, node_size=0)

# OPTION 2: if you want all the strongly connected components
# first flatten the list of sets of nodes
nodes = [y for x in nx.strongly_connected_components(G) if len(x) > 1 for y in x]
Gc = ox.utils_graph.induce_subgraph(G, nodes)
print(len(Gc)) #9551
fig, ax = ox.plot_graph(Gc, node_size=0)

编辑:@yatu 对强连接组件的大小提出了一个很好的观点。我在上面编辑了一行,只保留超过 1 个节点的强连接组件。