新手求助:如何用OSMnx获取最大入度节点及其经纬度?
Hey there! Let's work through your problem step by step to get you the node with the highest in-degree centrality, plus its latitude and longitude.
1. Do you need a directed graph for in-degree centrality?
Absolutely! In-degree only makes sense for directed graphs (where edges have a direction, like one-way streets). Good news: when you use network_type='drive_service', OSMnx automatically creates a directed DiGraph for you, since motorized roads often have direction restrictions. You can double-check this with:
print(type(G)) # Should output <class 'networkx.classes.digraph.DiGraph'>
If for some reason you end up with an undirected graph, you can convert it to directed with G = G.to_directed(), but this shouldn't be needed for drive networks.
2. Why isn't in_degree_centrality in extended_stats?
OSMnx's extended_stats function doesn't include in-degree centrality by default—no big deal though! We can just calculate it directly using NetworkX's built-in nx.in_degree_centrality() function, which works perfectly on directed graphs.
3. Fixing your code to get the max in-degree node
Your current code has a couple of small bugs when calculating in-degree centrality. Let's fix those and add the coordinate retrieval:
First, calculate the in-degree centrality correctly:
# Calculate in-degree centrality on the original directed graph in_degree_centrality = nx.in_degree_centrality(G) # Find the node with the highest value max_node, max_in_deg = max(in_degree_centrality.items(), key=lambda x: x[1])
Next, grab the node's latitude and longitude. Important: use the original unprojected graph G for this—G_projected uses UTM (metric) coordinates, not the geographic lat/lon you need. OSMnx stores unprojected coordinates as x (longitude) and y (latitude) in node attributes:
node_lat = G.nodes[max_node]['y'] node_lon = G.nodes[max_node]['x']
4. Full adjusted code
Here's the complete, working version of your code with all fixes and the coordinate output:
import osmnx as ox, networkx as nx, matplotlib.cm as cm, pandas as pd, numpy as np place = 'City of Lethbridge, Alberta, Canada' gdf = ox.gdf_from_place(place) area = ox.project_gdf(gdf).unary_union.area # Create directed drive-service graph G = ox.graph_from_place(place, network_type='drive_service') # Calculate and merge basic/extended stats stats = ox.basic_stats(G, area=area) extended_stats = ox.extended_stats(G, ecc=True, bc=True, cc=True) for key, value in extended_stats.items(): stats[key] = value # Unpack street node counts/proportions into individual stats for k, count in stats['streets_per_node_counts'].items(): stats[f'int_{k}_count'] = count for k, proportion in stats['streets_per_node_proportion'].items(): stats[f'int_{k}_prop'] = proportion del stats['streets_per_node_counts'] del stats['streets_per_node_proportion'] # Convert stats to DataFrame (optional) pd.DataFrame(pd.Series(stats)).T # Calculate in-degree centrality and find the top node in_degree_centrality = nx.in_degree_centrality(G) max_node, max_in_deg = max(in_degree_centrality.items(), key=lambda x: x[1]) # Get the node's geographic coordinates node_lat = G.nodes[max_node]['y'] node_lon = G.nodes[max_node]['x'] # Print your results print(f"Node ID with highest in-degree centrality: {max_node}") print(f"In-degree centrality value: {max_in_deg:.4f}") print(f"Latitude: {node_lat:.6f}, Longitude: {node_lon:.6f}") # Optional: Plot the highlighted node on the map G_projected = ox.project_graph(G) node_colors = ['red' if node == max_node else '#336699' for node in G_projected.nodes()] node_sizes = [50 if node == max_node else 8 for node in G_projected.nodes()] fig, ax = ox.plot_graph(G_projected, node_size=node_sizes, node_color=node_colors, node_zorder=2)
Quick reminders:
- Stick to the original unprojected graph
Gwhen pulling lat/lon—G_projecteduses metric coordinates that aren't useful for geographic location. - If you ever work with an undirected graph (like a walking network), in-degree centrality will be identical to regular degree centrality, since there's no direction to edges.
内容的提问来源于stack exchange,提问作者sola

