如何使用Python geopandas按GIS shapefile第三列值为GPS点分配独特色彩绘图
问题原因及修正方案
核心问题
你当前代码的核心问题是仅生成了点几何对象,没有将普通的CSV DataFrame转为GeoDataFrame,直接对pandas DataFrame调用plot方法不会按空间坐标绘制点,自然得不到预期结果。
还有几个次要问题也会影响输出:
- 仅定义了crs参数,但没有实际赋值给GPS点数据,若shapefile的坐标系和GPS的WGS84不一致,会出现坐标错位
- 等级4的图例标签错误写成了
Grade 3,会导致图例重复 - 等级3的白色点在灰色底图上辨识度极低,建议加黑色描边优化显示
修正后完整代码
import pandas as pd import matplotlib.pyplot as plt import geopandas as gpd from shapely.geometry import Point %matplotlib inline # 读取底图shp Dist_shp = r'D:\shapefile.shp' shp_f = gpd.read_file(Dist_shp) # 读取GPS数据并转为GeoDataFrame gps_location = pd.read_csv(r'D:\plotGPS.csv') crs = 'EPSG:4326' # 新版geopandas推荐字符串格式定义crs # 生成带空间信息的GeoDataFrame gps_gdf = gpd.GeoDataFrame( gps_location, geometry = [Point(xy) for xy in zip(gps_location["LONGITUDE"], gps_location["LATITUDE"])], crs = crs ) # 统一GPS和底图的坐标系,避免坐标偏移 gps_gdf = gps_gdf.to_crs(shp_f.crs) # 绘图 fig,ax = plt.subplots(figsize = (25,25)) # 绘制底图 shp_f.plot(ax=ax, alpha=0.4, color="grey") # 按等级绘制不同颜色的点,白色点加黑色描边提高辨识度 gps_gdf[gps_gdf['thirdcolumnvalue'] == 1].plot(ax=ax, markersize=10, color='red', marker="o", label="Grade 1") gps_gdf[gps_gdf['thirdcolumnvalue'] == 2].plot(ax=ax, markersize=10, color='green', marker="^", label="Grade 2") gps_gdf[gps_gdf['thirdcolumnvalue'] == 3].plot(ax=ax, markersize=10, color='white', marker="^", edgecolor='black', label="Grade 3") gps_gdf[gps_gdf['thirdcolumnvalue'] == 4].plot(ax=ax, markersize=10, color='black', marker="^", label="Grade 4") gps_gdf[gps_gdf['thirdcolumnvalue'] == 5].plot(ax=ax, markersize=10, color='yellow', marker="^", label="Grade 5") plt.legend(prop={'size':15}) plt.show()
内容的提问来源于stack exchange,提问作者SKC
相关产品推荐
相关产品推荐

