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

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

Python Geopandas: Exclude French Guiana from Europe Map

问题

  1. import geopandas as gpd
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  5. europe = europe[europe.continent == 'Europe']
  6. # europe = europe[europe.name != 'France']
  7. data = pd.read_csv('HICP_EU_bycountry_12_2022.csv', delimiter=';')
  8. data = data[['Area', 'Rate']]
  9. merged_data = europe.merge(data, left_on='name', right_on='Area', how='left')
  10. fig, ax = plt.subplots(figsize=(10, 6))
  11. merged_data.plot(column='Rate', cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
  12. ax.set_title('Inflation Rates in Europe', fontsize=16)
  13. ax.set_axis_off()
  14. for idx, row in merged_data.iterrows():
  15. rate = row['Rate']
  16. if not pd.isna(rate):
  17. ax.annotate(text=str(rate), xy=row['geometry'].centroid.coords[0], horizontalalignment='center', fontsize=8)
  18. ax.set_facecolor('#f7f7f7')
  19. 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:

  1. import geopandas as gpd
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  5. europe = europe[europe.continent == 'Europe']
  6. #europe = europe[europe.name != 'France']
  7. data = pd.read_csv('HICP_EU_bycountry_12_2022.csv', delimiter=';')
  8. data = data[['Area', 'Rate']]
  9. merged_data = europe.merge(data, left_on='name', right_on='Area', how='left')
  10. fig, ax = plt.subplots(figsize=(10, 6))
  11. merged_data.plot(column='Rate', cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
  12. ax.set_title('Inflation Rates in Europe', fontsize=16)
  13. ax.set_axis_off()
  14. for idx, row in merged_data.iterrows():
  15. rate = row['Rate']
  16. if not pd.isna(rate):
  17. ax.annotate(text=str(rate), xy=row['geometry'].centroid.coords[0], horizontalalignment='center', fontsize=8)
  18. ax.set_facecolor('#f7f7f7')
  19. plt.show()

答案1

得分: 1

  1. # 导入必要的库
  2. import geopandas as gpd
  3. import matplotlib.pyplot as plt
  4. from shapely.geometry import Polygon, MultiPolygon
  5. # 从 geopandas 库中加载欧洲地图数据
  6. world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  7. europe = world[world.continent == 'Europe']
  8. # 从法国的 MultiPolygon 中提取点并创建新的 Polygon 以替换 geopandas 中的 MultiPolygon
  9. tmp = [x.replace(')','') for x in str(europe.loc[43,'geometry']).split('((')[1:]][1]
  10. tmp2 = [x.split(' ') for x in tmp.split(', ')][:-1]
  11. tmp3 = [(float(x[0]), float(x[1])) for x in tmp2]
  12. France_mainland = Polygon(tmp3)
  13. 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.

  1. import geopandas as gpd
  2. import matplotlib.pyplot as plt
  3. from shapely.geometry import Polygon, MultiPolygon
  4. # Load Europe map data from the geopandas library
  5. world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  6. europe = world[world.continent == 'Europe']
  7. # Exclude French Guiana from the map (also Corsika though),
  8. tmp = [x.replace(')','') for x in str(europe.loc[43,'geometry']).split('((')[1:]][1]
  9. tmp2 = [x.split(' ') for x in tmp.split(', ')][:-1]
  10. tmp3 = [(float(x[0]),float(x[1])) for x in tmp2]
  11. France_mainland = Polygon(tmp3)
  12. 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上生成。

  1. import geopandas as gpd
  2. import pandas as pd
  3. from shapely.geometry import Polygon
  4. import matplotlib.pyplot as plt
  5. # 步骤1 #
  6. # 从bbox坐标创建多边形 https://stackoverflow.com/a/68741143/18253502
  7. def make_bbox(long0, lat0, long1, lat1):
  8. return Polygon([[long0, lat0],
  9. [long1, lat0],
  10. [long1, lat1],
  11. [long0, lat1]])
  12. # 涵盖欧洲和俄罗斯的坐标,使用http://bboxfinder.com生成
  13. bbox = make_bbox(-36.210938, 28.304381, 197.226563, 81.361287)
  14. ## 或者,可以将其切割为更标准的欧洲范围
  15. ## 排除中东部的俄罗斯
  16. # bbox = make_bbox(-36.386719, 29.228890, 60.292969, 74.543330)
  17. # 步骤2 #
  18. # 转换为GeoDataFrame
  19. bbox_gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[bbox])
  20. # 步骤3 #
  21. # 加载欧洲
  22. europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  23. europe = europe[europe.continent == 'Europe']
  24. # 使用bbox作为欧洲的切割边界
  25. europe = europe.overlay(bbox_gdf, how="intersection")
  26. 现在`europe`已经被切割到bbox的范围内
  27. # 绘制结果
  28. fig, ax = plt.subplots(figsize=(15, 10)
  29. europe.plot(linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
  30. ax.set_title('切割范围', fontsize=16)
  31. ax.set_axis_off()
  32. ax.set_facecolor('#f7f7f7')
  33. 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.

  1. import geopandas as gpd
  2. import pandas as pd
  3. from shapely.geometry import Polygon
  4. import matplotlib.pyplot as plt
  5. # STEP 1 #
  6. # Make polygon from bbox coordinates https://stackoverflow.com/a/68741143/18253502
  7. def make_bbox(long0, lat0, long1, lat1):
  8. return Polygon([[long0, lat0],
  9. [long1,lat0],
  10. [long1,lat1],
  11. [long0, lat1]])
  12. # Coords covering Europe & Russia made with http://bboxfinder.com
  13. bbox = make_bbox(-36.210938,28.304381,197.226563,81.361287)
  14. ## Alternatively, can clip to more standard European extent
  15. ## with Central/Eastern Russia excluded
  16. # bbox = make_bbox(-36.386719,29.228890,60.292969,74.543330)
  17. # STEP 2 #
  18. # Convert to gdf
  19. bbox_gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry = [bbox])
  20. # STEP 3 #
  21. # Load europe
  22. europe = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
  23. europe = europe[europe.continent == 'Europe']
  24. # Use bbox as clipping border for Europe
  25. europe = europe.overlay(bbox_gdf, how="intersection")

Now europe has been clipped to the bbox extent:

  1. # plot result
  2. fig, ax = plt.subplots(figsize=(15,10))
  3. europe.plot(linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
  4. ax.set_title('Clipped Extent', fontsize=16)
  5. ax.set_axis_off()
  6. ax.set_facecolor('#f7f7f7')
  7. 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:

确定