Geopandas绘制墨西哥布鲁氏菌病地图空白问题求助
问题:墨西哥布鲁氏菌病地图绘制后显示空白
我是自学编程的新手,在此为可能造成的困惑致歉。我需要制作一张带频率信息的墨西哥布鲁氏菌病地图,已将shapefile文件与dbf文件合并获取州级信息,再与包含地图着色数据的Excel文件合并后绘图,但地图显示空白,尝试多种网络方案仍未解决。
附上我的代码:
import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt proj4_string = ( "\"+proj=lcc +lat_1=17.5 +lat_2=29.5 +lat_0=12 +lon_0=-102 +x_0=2500000 +y_0=0 \" "\"+a=6378137 +rf=298.257222101 +units=m +no_defs\" ) mx = gpd.read_file("\"/content/enti.shp\"") mx.crs = proj4_string mx.plot() print(mx) print(mx.columns) # Read the Excel data excel_path = '/content/BH2020.xlsx' df20 = pd.read_excel(excel_path) merged_data = pd.merge(mx, df20, left_on='CVE_ENT_x', right_on='Entidades', how='left') print(merged_data) # Create the plot merged_data.plot(column='TOTALES', cmap='Reds', linewidth=0.8, edgecolor='0.8', legend=True) # Set the title plt.title('Brucelosis en México 2020') # Show the plot plt.show()
最终结果:地图显示空白(无任何地理图形或着色)
问题排查与解决步骤
1. 修正投影字符串与CRS设置
你的proj4_string包含多余嵌套双引号,会导致坐标参考系统(CRS)设置失效,同时推荐使用set_crs()方法替代直接赋值:
# 修正投影字符串格式 proj4_string = ( "+proj=lcc +lat_1=17.5 +lat_2=29.5 +lat_0=12 +lon_0=-102 +x_0=2500000 +y_0=0 " "+a=6378137 +rf=298.257222101 +units=m +no_defs" ) # 正确设置CRS mx = mx.set_crs(proj4_string, allow_override=True)
2. 修复文件路径读取错误
gpd.read_file()的路径被嵌套双引号包裹,会导致文件读取异常,改为:
mx = gpd.read_file("/content/enti.shp")
3. 确保数据合并匹配有效
地图空白大概率是合并后TOTALES列存在大量空值,先检查空值数量:
print(merged_data['TOTALES'].isna().sum())
如果空值过多,说明CVE_ENT_x和Entidades的匹配键格式不统一,需先对齐格式(比如数字转字符串):
mx['CVE_ENT_x'] = mx['CVE_ENT_x'].astype(str) df20['Entidades'] = df20['Entidades'].astype(str) merged_data = pd.merge(mx, df20, left_on='CVE_ENT_x', right_on='Entidades', how='left')
4. 调整绘图视野范围
如果图形绘制但处于视野外,添加自动缩放:
ax = merged_data.plot(column='TOTALES', cmap='Reds', linewidth=0.8, edgecolor='0.8', legend=True) ax.autoscale()
完整修正代码示例
import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt # 修正投影字符串 proj4_string = ( "+proj=lcc +lat_1=17.5 +lat_2=29.5 +lat_0=12 +lon_0=-102 +x_0=2500000 +y_0=0 " "+a=6378137 +rf=298.257222101 +units=m +no_defs" ) # 读取并设置CRS mx = gpd.read_file("/content/enti.shp") mx = mx.set_crs(proj4_string, allow_override=True) # 先测试基础地图是否显示 mx.plot() plt.show() print(mx.columns) # 读取Excel数据并统一匹配格式 df20 = pd.read_excel('/content/BH2020.xlsx') mx['CVE_ENT_x'] = mx['CVE_ENT_x'].astype(str) df20['Entidades'] = df20['Entidades'].astype(str) # 合并数据并检查有效数据量 merged_data = pd.merge(mx, df20, left_on='CVE_ENT_x', right_on='Entidades', how='left') print(f"有效着色数据行数:{merged_data['TOTALES'].notna().sum()}") # 绘制带着色的地图 ax = merged_data.plot(column='TOTALES', cmap='Reds', linewidth=0.8, edgecolor='0.8', legend=True) ax.autoscale() plt.title('Brucelosis en México 2020') plt.show()
内容的提问来源于stack exchange,提问作者Isabela Ruelas
相关产品推荐
相关产品推荐

