我是编程新手,我正在自学,所以对于任何困惑,我深表歉意...... 我需要用频率制作这张地图,并且我有一个 shapefile,我将 shapefile 合并到 dbf 文件,这样我就有了我需要的状态信息。然后,我将其合并到我的 Excel 文件中,该文件包含使地图“着色”所需的数据并绘制了绘图,问题是我的地图没有显示,它是空白的!我真的不知道该怎么办,我已经尝试了网上能找到的一切......
我分享我的代码:
import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
import os
import dbfpy
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()
# Read the updated shapefile
shapefile_path = '/content/enti.shp'
mx = gpd.read_file(shapefile_path)
# Check if the associated .dbf file exists and load it
import dbf
dfb_path= '/content/enti.dbf'
import os
import pandas as pd
from dbfread import DBF
dbf_path = '/content/enti.dbf'
if os.path.exists(dbf_path):
dbf = DBF(dbf_path, char_decode_errors='ignore')
df_dbf = pd.DataFrame(iter(dbf))
print(df_dbf)
else:
print(f"The file {dbf_path} does not exist.")
import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
# Read the updated shapefile
shapefile_path = '/content/enti.shp'
mx = gpd.read_file(shapefile_path)
print(mx)
df_dbf.drop_duplicates(inplace=True)
mex = pd.merge(mx, df_dbf[['CVEGEO', 'NOMGEO', 'CVE_ENT']], left_on=['CVEGEO', 'NOMGEO'], right_on=['CVEGEO', 'NOMGEO'], how='left')
# Read the Excel data
excel_path = '/content/BH2020.xlsx'
df20 = pd.read_excel(excel_path)
merged_data = pd.merge(mex, df20, left_on='CVE_ENT_x', right_on='Entidades', how='left')
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
geometry_column = 'geometry'
# 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()
没有数据有点困难,如果能分享一下就更实用了。
无论如何,您已经可以大大简化脚本,这已经很有帮助了。
mx = gpd.read_file("/content/enti.shp")
调用已读取 .dbf。如果您在阅读 .shp 后输入 print(mx)
或 print(mx.columns)
,您就会看到这一点。mx.crs = proj4_string
设置crs后再次读取shp,crs将再次丢失,因为这样设置crs不会对磁盘上的文件进行任何更改。因此,您还需要删除第二个mx = gpd.read_file(shapefile_path)
。这是上述更改后的相关代码:
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()