基于Shapefile中150个行政区多边形计算街道网络方向与熵
解决方案步骤
1. 加载行政区Shapefile
首先用GeoPandas读取你的Shapefile,确保坐标系转换为WGS84(EPSG:4326)——这是OSMnx默认使用的坐标系,避免因坐标不匹配导致的错误。
2. 批量处理每个行政区
遍历每个行政区多边形,依次完成街道网络提取、方向计算、熵值统计,并保存结果。相比用graph_from_bbox,直接用graph_from_polygon能更精准地匹配行政区边界,避免包含区域外的街道。
完整代码示例
import geopandas as gpd import osmnx as ox import matplotlib.pyplot as plt from tqdm import tqdm # 可选,用于显示处理进度 # 配置参数 network_type = "all" weight_by_length = False output_dir = "C:/AC/Snt_GC/ward_orientation_plots/" # 替换为你的输出目录 # 1. 加载Shapefile wards_gdf = gpd.read_file("你的Shapefile路径.shp") # 确保坐标系为WGS84 if wards_gdf.crs != "EPSG:4326": wards_gdf = wards_gdf.to_crs(epsg=4326) # 初始化存储结果的列 wards_gdf["orientation_entropy"] = None # 2. 遍历每个行政区 for idx, row in tqdm(wards_gdf.iterrows(), total=len(wards_gdf)): ward_no = row["Ward_No"] polygon = row["geometry"] try: # 基于多边形提取街道网络 G = ox.graph_from_polygon( polygon, network_type=network_type, simplify=True, clean_periphery=True, retain_all=False ) # 转换为无向图并添加方向角 Gu = ox.add_edge_bearings(ox.get_undirected(G)) # 计算方向熵 entropy = ox.bearing.orientation_entropy(Gu, num_bins=36, min_length=0, weight=None) wards_gdf.at[idx, "orientation_entropy"] = entropy # 绘制并保存方向玫瑰图 fig, ax = ox.plot_orientation(Gu) fig.suptitle(f"Ward {ward_no}", fontsize=30, y=1) fig.tight_layout() fig.subplots_adjust(hspace=0.35) fig.savefig( f"{output_dir}street-orientations_ward_{ward_no}.png", facecolor="w", dpi=200, bbox_inches="tight" ) plt.close(fig) except Exception as e: print(f"处理Ward {ward_no}时出错: {str(e)}") continue # 保存包含熵值的Shapefile wards_gdf.to_file("你的结果输出路径.shp")
关于你现有代码的正确性
你当前针对单个bbox的代码是正确的:它能成功提取指定范围内的街道网络,计算方向角和熵值,并生成玫瑰图。但改用graph_from_polygon能更精准匹配行政区边界,避免包含区域外的街道数据,结果会更准确。
内容的提问来源于stack exchange,提问作者joseph_k
相关产品推荐
相关产品推荐

