我正在用 python geopandas 为欧洲地图编写代码。
我目前正面临法属圭亚那的问题。我不想让它显示在地图上,但是,我找不到将它与法国分离的方法。
这是我的代码:
import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
europe = europe[europe.continent == 'Europe']
#europe = europe[europe.name != 'France']
data = pd.read_csv('HICP_EU_bycountry_12_2022.csv', delimiter=';')
data = data[['Area', 'Rate']]
merged_data = europe.merge(data, left_on='name', right_on='Area', how='left')
fig, ax = plt.subplots(figsize=(10, 6))
merged_data.plot(column='Rate', cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
ax.set_title('Inflation Rates in Europe', fontsize=16)
ax.set_axis_off()
for idx, row in merged_data.iterrows():
rate = row['Rate']
if not pd.isna(rate):
ax.annotate(text=str(rate), xy=row['geometry'].centroid.coords[0], horizontalalignment='center', fontsize=8)
ax.set_facecolor('#f7f7f7')
plt.show()
由于此数据集中的领土之间没有分隔,我们可以使用边界框(bbox)作为剪辑将多边形切割成您想要的大小。
这相对简单,但我们需要一个小函数和来自 Shapely 的
Polygon
类来将 bbox 转换为形状。为了实现这一点,我们需要完成以下步骤:
europe
.来自 https://stackoverflow.com/a/68741143/18253502,我们可以将 bbox 坐标转换为匀称的多边形。 Bbox坐标可以在http://bboxfinder.com.
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
# STEP 1 #
# Make polygon from bbox coordinates https://stackoverflow.com/a/68741143/18253502
def make_bbox(long0, lat0, long1, lat1):
return Polygon([[long0, lat0],
[long1,lat0],
[long1,lat1],
[long0, lat1]])
# Coords covering Europe & Russia made with http://bboxfinder.com
bbox = make_bbox(-36.210938,28.304381,197.226563,81.361287)
## Alternatively, can clip to more standard European extent
## with Central/Eastern Russia excluded
# bbox = make_bbox(-36.386719,29.228890,60.292969,74.543330)
# STEP 2 #
# Convert to gdf
bbox_gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry = [bbox])
# STEP 3 #
# Load europe
europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
europe = europe[europe.continent == 'Europe']
# Use bbox as clipping border for Europe
europe = europe.overlay(bbox_gdf, how="intersection")
现在
europe
已经裁剪到bbox范围:
# plot result
fig, ax = plt.subplots(figsize=(15,10))
europe.plot(linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
ax.set_title('Clipped Extent', fontsize=16)
ax.set_axis_off()
ax.set_facecolor('#f7f7f7')
plt.show()
请注意,俄罗斯的东端不见了,因为它环绕到另一个经度(有关更多详细信息,请参见https://stackoverflow.com/a/71408567/18253502)。