繪製多個圖層
pandas 的另一個常見功能是篩選 DataFrame:根據條件取得列的子集合(該條件會產生布林遮罩)。
在這個練習中,你會先取出所有非洲餐廳的子集合,接著建立一個多圖層的繪圖。在這種圖中,我們會把多個 GeoDataFrame 視覺化後疊加在同一張圖上。若要新增一個圖層,可以在 GeoDataFrame 的 plot() 方法中使用 ax 關鍵字,傳入一個 matplotlib 的座標軸物件。
餐廳資料已載入為 restaurants 這個 GeoDataFrame。GeoPandas 已以 geopandas 匯入,matplotlib.pyplot 以 plt 匯入。
本練習屬於課程
在 Python 中處理地理空間資料
練習說明
- 選出所有
type為 'African restaurant' 的列作為子集合,並命名為african_restaurants。 - 繪製所有餐廳,並使用統一的灰色。記得把一個 matplotlib 座標軸物件傳給
plot()方法。 - 以紅色新增第二個圖層,只顯示非洲餐廳。常見顏色可以直接用英文名稱,例如 'red' 與 'grey'。
- 針對該 matplotlib 座標軸物件呼叫
set_axis_off()方法以移除外框。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Load the restaurants dataset
restaurants = geopandas.read_file("paris_restaurants.geosjon")
# Take a subset of the African restaurants
african_restaurants = ____
# Make a multi-layered plot
fig, ax = plt.subplots(figsize=(10, 10))
restaurants.____
african_restaurants.____
# Remove the box, ticks and labels
ax.____
plt.show()