Python Geopandas: 从欧洲地图中排除法属圭亚那

huangapple go评论63阅读模式
英文:

Python Geopandas: Exclude French Guiana from Europe Map

问题

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()
英文:

I am writing a code for a map of europe with python geopandas.

I am currently facing a problem with French Guiana. I don't want it to display in the map, however, I don't find a way to detach it from France.

Here is my code:

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()

答案1

得分: 1

# 导入必要的库
import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon, MultiPolygon

# 从 geopandas 库中加载欧洲地图数据
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
europe = world[world.continent == 'Europe']

# 从法国的 MultiPolygon 中提取点并创建新的 Polygon 以替换 geopandas 中的 MultiPolygon
tmp = [x.replace(')','') for x in str(europe.loc[43,'geometry']).split('((')[1:]][1]
tmp2 = [x.split(' ') for x in tmp.split(', ')][:-1]
tmp3 = [(float(x[0]), float(x[1])) for x in tmp2]
France_mainland = Polygon(tmp3)
europe.loc[europe['name'] == 'France', 'geometry'] = France_mainland
英文:

Alternatively, you can mess around with the MultiPolygon of France including Guiana and Corse. I extract the points from the polygon for France and make a new polygon to replace the multipolygon in the geo panda.

import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon, MultiPolygon

# Load Europe map data from the geopandas library
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
europe = world[world.continent == 'Europe']

# Exclude French Guiana from the map (also Corsika though), 
tmp = [x.replace(')','') for x in str(europe.loc[43,'geometry']).split('((')[1:]][1]
tmp2 = [x.split(' ') for x in tmp.split(', ')][:-1]
tmp3 = [(float(x[0]),float(x[1])) for x in tmp2]
France_mainland = Polygon(tmp3)
europe.loc[europe['name']=='France','geometry'] = France_mainland 

答案2

得分: 0

由于该数据集中没有领土之间的分离,我们可以使用边界框(bbox)来切割多边形以满足您的需求。

这相对简单,但我们需要一个小函数和来自Shapely的Polygon类来将bbox转换为形状。为了实现这一点,我们需要完成以下步骤:

  1. 获取您所需区域的bbox
  2. 将其转换为GeoDataFrame
  3. 用它来切割europe

从https://stackoverflow.com/a/68741143/18253502,我们可以将bbox坐标转换为Shapely多边形。bbox坐标可以在http://bboxfinder.com上生成。

import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt

# 步骤1 #
# 从bbox坐标创建多边形 https://stackoverflow.com/a/68741143/18253502
def make_bbox(long0, lat0, long1, lat1):
    return Polygon([[long0, lat0],
                    [long1, lat0],
                    [long1, lat1],
                    [long0, lat1]])

# 涵盖欧洲和俄罗斯的坐标,使用http://bboxfinder.com生成
bbox = make_bbox(-36.210938, 28.304381, 197.226563, 81.361287)
## 或者,可以将其切割为更标准的欧洲范围
## 排除中东部的俄罗斯
# bbox = make_bbox(-36.386719, 29.228890, 60.292969, 74.543330)

# 步骤2 #
# 转换为GeoDataFrame
bbox_gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[bbox])

# 步骤3 #
# 加载欧洲
europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
europe = europe[europe.continent == 'Europe']

# 使用bbox作为欧洲的切割边界
europe = europe.overlay(bbox_gdf, how="intersection")

现在`europe`已经被切割到bbox的范围内

# 绘制结果
fig, ax = plt.subplots(figsize=(15, 10)

europe.plot(linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
ax.set_title('切割范围', fontsize=16)
ax.set_axis_off()
ax.set_facecolor('#f7f7f7')

plt.show()

请注意,俄罗斯的东端缺失,因为它绕到了另一条经度(详见https://stackoverflow.com/a/71408567/18253502以获取更多详细信息)。

英文:

As there is no separation between territories in this dataset, we can cut the polygons to your desired size using a bounding box (bbox) as a clip.

This is relatively simple, but we will need a small function and the Polygon class from Shapely to convert a bbox to a shape. In order to achieve this, we need to complete the following steps:

  1. Get a bbox of your desired area
  2. Convert it to a GeoDataFrame
  3. Use it to clip europe.

From https://stackoverflow.com/a/68741143/18253502, we can convert bbox coordinates to a shapely Polygon. Bbox coordinates can be made at 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")

Now europe has been clipped to the bbox extent:

# 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()

Python Geopandas: 从欧洲地图中排除法属圭亚那

Note that the Eastern tip of Russia is missing, as it wraps around to the other Longitude (see https://stackoverflow.com/a/71408567/18253502 for more details).

huangapple
  • 本文由 发表于 2023年2月18日 18:10:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定