GeoPandas入門 | 05-Python可視化空間數據

05-Python可視化空間數據

源代碼請看此處

%matplotlib inline

import pandas as pd
import geopandas

import matplotlib.pyplot as plt
countries = geopandas.read_file("zip://data/ne_110m_admin_0_countries.zip")
cities = geopandas.read_file("zip://data/ne_110m_populated_places.zip")
rivers = geopandas.read_file("zip://data/ne_50m_rivers_lake_centerlines.zip")

5.1 GeoPandas的可視化函數

基礎繪圖

countries.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f7e787c93c8>

調整地圖大小

countries.plot(figsize=(15,15))
<matplotlib.axes._subplots.AxesSubplot at 0x7f7e764cccc0>

png

移除邊框及x,y座標

ax=countries.plot(figsize=(15,15))
ax.set_axis_off()

png

根據列值進行着色

首先創建一個新的人均國內生產總值列

countries=countries[(countries['pop_est']>0)&(countries['name']!="Antarctica")]
countries['gdp_per_cap'] = countries['gdp_md_est'] / countries['pop_est'] * 100

現在可以使用這個列來給多邊形着色:

ax = countries.plot(figsize=(15, 15), column='gdp_per_cap')
ax.set_axis_off()

png

ax = countries.plot(figsize=(15, 15), column='gdp_per_cap', scheme='quantiles', legend=True) # scheme 分級方法
ax.set_axis_off()

png

將多個GeoDataframe的數據同時可視化

.plot方法返回一個matplotlib的Axes對象,然後可以通過ax=關鍵字重新使用這個對象爲該圖添加額外的圖層

ax=countries.plot(figsize=(15,15))
cities.plot(ax=ax,color='red',markersize=10)
ax.set_axis_off()

png

ax=countries.plot(edgecolor='k',facecolor='none',figsize=(15,15))
rivers.plot(ax=ax)
cities.plot(ax=ax,color='C1')
# ax.set(xlim=(70,135),ylim=(0,55))
ax.set_axis_off()

png

使用contextily添加背景圖

該包允許輕鬆地將基於Web-tile的背景圖(basemap)添加到的GeoPandas圖中

目前,唯一的要求是數據投影爲WebMercator(EPSG:3857)

cities_europe = cities[cities.within(countries[countries['continent'] == 'Europe'].unary_union)] 
# .unary_union: Returns a geometry containing the union of all geometries in the GeoSeries
cities_europe2 = cities_europe.to_crs(epsg=3857)
ax=cities_europe2.plot()

png

import contextily as ctx
ax=cities_europe2.plot(figsize=(10,6))
ctx.add_basemap(ax)

png

ax = cities_europe2.plot(figsize=(10, 6))
ctx.add_basemap(ax, source=ctx.providers.Stamen.TonerLite)

png

5.2 使用geoplot包進行可視化

與GeoDataFrames的基本.plot()方法相比,geoplot包提供了一些額外的功能

  • 高級繪圖API(有更多的繪圖類型)
  • 通過cartopy支持本地投影

https://residentmario.github.io/geoplot/index.html

# ! pip3 install geoplot
import sys
import geoplot
import geoplot.crs as gcrs
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={
    'projection': gcrs.Orthographic(central_latitude=35, central_longitude=116.0059)
})
geoplot.choropleth(countries, hue='gdp_per_cap', projection=gcrs.Orthographic(), ax=ax,
                   cmap='BuGn', linewidth=1, edgecolor='white')
ax.set_global()
ax.outline_patch.set_visible(True)
# ax.coastlines()
# Geometry must be a Point or LineString
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:7: DeprecationWarning: The outline_patch property is deprecated. Use GeoAxes.spines['geo'] or the default Axes properties instead.
  import sys

png

5.3 使用cartopy包進行可視化

使用cartopy

Cartopy是matplotlib的基礎製圖庫,它被geoplot用來提供投影

http://scitools.org.uk/cartopy/docs/latest/index.html

下面的例子取自文檔:http://geopandas.readthedocs.io/en/latest/gallery/cartopy_convert.html#sphx-glr-gallery-cartopy-convert-py

from cartopy import crs as ccrs
crs=ccrs.AlbersEqualArea()
crs_proj4=crs.proj4_init
countries_ae=countries.to_crs(crs_proj4)
countries_ae.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f7e56a852b0>

png

fig,ax=plt.subplots(subplot_kw={'projection':crs})
ax.add_geometries(countries_ae['geometry'],crs=crs)
<cartopy.mpl.feature_artist.FeatureArtist at 0x7f7e569b1080>

png

fig, ax = plt.subplots(subplot_kw={'projection': crs})
countries_ae['geometry'].plot(ax=ax)
<cartopy.mpl.geoaxes.GeoAxesSubplot at 0x7f7e568c34a8>

png

5.4 基於web的交互式可視化

現在有很多針對交互式網絡可視化的庫,可以處理地理空間數據:

另一個流行的在線地圖的javascript庫是Leaflet.js,這個庫在foliumipyleaflet包中有python接口

ipyleaflet的使用實例:

# ! pip3 install ipyleaflet
import ipyleaflet
m = ipyleaflet.Map(center=[48.8566, 2.3429], zoom=3)
geo_data = ipyleaflet.GeoData(
    geo_dataframe = countries,
    style={'color': 'black', 'fillColor': '#3366cc', 'opacity':0.05, 'weight':1.9, 'dashArray':'2', 'fillOpacity':0.6},
    hover_style={'fillColor': 'red' , 'fillOpacity': 0.2},
    name = 'Countries')
m.add_layer(geo_data)
m
# jupyter labextension install @jupyter-widgets/jupyterlab-manager
Map(center=[48.8566, 2.3429], controls=(ZoomControl(options=['position', 'zoom_in_text', 'zoom_in_title', 'zoo…

更多信息:https://ipyleaflet.readthedocs.io/en/latest/api_reference/geodata.html

folium的使用實例

import folium
m = folium.Map([39, 116], zoom_start=6, tiles="OpenStreetMap")
folium.GeoJson(countries).add_to(m)
folium.GeoJson(cities).add_to(m)
m
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章