用 geopandas 为特定国家着色

Bra*_*las 3 pandas graph-coloring geopandas

我想绘制非洲大陆某些设施的位置地图,我可以使用下面的代码来完成此操作。现在我想只对特定国家进行着色(以纳米比亚为例),以使另一次分析更清晰。有谁知道这样做的干净方法吗?预先非常感谢您。

最好的,布拉姆

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

data = pd.read_csv("Repair_yards_africa.csv")

base = world[world.continent == 'Africa'].plot(color='white', edgecolor='black')

data['Coordinates'] = list(zip(data.lon, data.lat))
data['Coordinates'] = data['Coordinates'].apply(Point)
geodata = gpd.GeoDataFrame(data, geometry='Coordinates')
geodata.plot(ax=base, color='red', markersize=11)
plt.ylabel('Lattitude')
plt.xlabel('Longitude')
Run Code Online (Sandbox Code Playgroud)

swa*_*hai 8

这可能是“仅对特定国家进行着色的干净方式(以纳米比亚为例) ”。仅给出代码的相关部分。

import matplotlib.pyplot as plt
import geopandas as gpd
from descartes import PolygonPatch

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

def plotCountryPatch( axes, country_name, fcolor ):
    # plot a country on the provided axes
    nami = world[world.name == country_name]
    namigm = nami.__geo_interface__['features']  # geopandas's geo_interface
    namig0 = {'type': namigm[0]['geometry']['type'], \
              'coordinates': namigm[0]['geometry']['coordinates']}
    axes.add_patch(PolygonPatch( namig0, fc=fcolor, ec="black", alpha=0.85, zorder=2 ))

# plot the whole world
#ax2 = world.plot( figsize=(8,4), edgecolor=u'gray', cmap='Set2' )

# or plot Africa continent
ax2 = world[world.continent == 'Africa'].plot(figsize=(8,8), edgecolor=u'gray', cmap='Pastel1')

# then plot some countries on top
plotCountryPatch(ax2, 'Namibia', 'red')
plotCountryPatch(ax2, 'Libya', 'green')

# the place to plot additional vector data (points, lines)

plt.ylabel('Latitude')
plt.xlabel('Longitude')

#ax2.axis('scaled')
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果图:

在此输入图像描述

编辑

或者,可以通过这个较短版本的代码来生成该图。

import matplotlib.pyplot as plt
import geopandas as gpd
# from descartes import PolygonPatch

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# or plot Africa continent
ax2 = world[world.continent == 'Africa'].plot(figsize=(8,8), edgecolor=u'gray', cmap='Pastel1')

world[world.name == "Libya"].plot(edgecolor=u'gray', color='green', ax=ax2)
world[world.name == "Namibia"].plot(edgecolor=u'gray', color='red', ax=ax2)

# the place to plot additional vector data (points, lines)

plt.ylabel('Latitude')
plt.xlabel('Longitude')

#ax2.axis('scaled')
plt.show()
Run Code Online (Sandbox Code Playgroud)