Python中澳大利亚地图城市点绘制异常问题排查
问题排查与修复:澳大利亚城市点地图显示错位
错误原因分析
- CRS基准不匹配:城市的原始经纬度属于WGS84(EPSG:4326)地理坐标系,但代码中直接将城市GeoDataFrame的CRS设为EPSG:7844(GDA2020投影坐标系),导致坐标体系混乱。
- 绘图坐标错误:投影转换后,城市的实际绘图坐标已存储在
geometry字段中,但代码仍使用原始的longs和lats列(未投影的WGS84坐标),与shapefile的投影坐标不在同一空间参考系,造成点位错位。 - 不必要的手动设置shapefile CRS:
gpd.read_file会自动读取shapefile自带的CRS信息,手动覆盖可能引发潜在问题。
修复后的完整代码
import geopandas as gpd import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 定义城市数据 cities = ['Sydney', 'Melbourne', 'Brisbane', 'Perth', 'Adelaide', 'Gold Coast', 'Newcastle', 'Canberra', 'Wollongong', 'Sunshine Coast', 'Hobart', 'Alice Springs'] lats = [-33.865143, -37.813629, -27.469771, -31.953512, -34.928499, -28.016666, -32.916668, -35.282001, -34.4278, -26.6500, -42.8821, -23.6970] longs = [151.209900, 144.963165, 153.025124, 115.857048, 138.600739, 153.399994, 151.750000, 149.128998, 150.8931, 153.0500, 147.3272, 133.8836] priority = np.random.randint(1, 6, size=len(cities)) # 创建DataFrame data = {'cityname': cities, 'lats': lats, 'longs': longs, 'priority': priority} df = pd.DataFrame(data) # 加载澳大利亚shapefile(自动读取CRS) australia = gpd.read_file('STE_2021_AUST_SHP_GDA2020/STE_2021_AUST_GDA2020.shp') # 创建城市GeoDataFrame,明确原始经纬度的CRS为WGS84(EPSG:4326) gdf_cities = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longs, df.lats), crs='epsg:4326') # 转换城市坐标到shapefile的CRS gdf_cities = gdf_cities.to_crs(australia.crs) # 空间关联城市与对应的行政区 gdf_cities = gpd.sjoin(gdf_cities, australia, predicate='within') # 绘图设置 sns.set_style("whitegrid") fig, ax = plt.subplots(figsize=(10, 10)) # 使用投影后的geometry坐标绘制城市点 gdf_cities.plot(ax=ax, column='priority', markersize=100, legend=True, cmap='viridis') # 绘制澳大利亚背景地图 australia.plot(ax=ax, color='lightgrey', edgecolor='white') # 设置标题与坐标轴 plt.title('澳大利亚城市优先级分布图') plt.xlabel('投影坐标系X') plt.ylabel('投影坐标系Y') # 隐藏坐标轴刻度(可选,投影坐标数值无直观地理意义) ax.set_xticks([]) ax.set_yticks([]) plt.show()
关键修复点说明
- 明确城市原始坐标的CRS为EPSG:4326,再转换到shapefile的CRS,确保坐标基准统一。
- 绘图时使用
gdf_cities.plot()直接调用GeoDataFrame的绘图方法,自动使用投影后的geometry坐标,替代原代码中使用原始未投影坐标的错误方式。 - 保留shapefile自动读取的CRS,不手动覆盖,避免人为错误。
内容的提问来源于stack exchange,提问作者Lobbie
相关产品推荐
相关产品推荐

