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()
调整地图大小
countries.plot(figsize=(15,15))
移除边框及x,y坐标
ax=countries.plot(figsize=(15,15))
ax.set_axis_off()
根据列值进行着色
首先创建一个新的人均国内生产总值列
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()
ax = countries.plot(figsize=(15, 15), column='gdp_per_cap', scheme='quantiles', legend=True) # scheme 分级方法
ax.set_axis_off()
将多个GeoDataframe的数据同时可视化
.plot
方法返回一个matplotlib的Axes对象,然后可以通过 ax=
关键字重新使用这个对象为该图添加额外的图层
ax=countries.plot(figsize=(15,15))
cities.plot(ax=ax,color='red',markersize=10)
ax.set_axis_off()
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()
使用 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()
import contextily as ctx
ax=cities_europe2.plot(figsize=(10,6))
ctx.add_basemap(ax)
ax = cities_europe2.plot(figsize=(10, 6))
ctx.add_basemap(ax, source=ctx.providers.Stamen.TonerLite)
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
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()
fig,ax=plt.subplots(subplot_kw={'projection':crs})
ax.add_geometries(countries_ae['geometry'],crs=crs)
fig, ax = plt.subplots(subplot_kw={'projection': crs})
countries_ae['geometry'].plot(ax=ax)
5.4 基于web的交互式可视化
现在有很多针对交互式网络可视化的库,可以处理地理空间数据:
- Bokeh: https://bokeh.pydata.org/en/latest/docs/gallery/texas.html
- GeoViews (other interface to Bokeh/matplotlib): http://geo.holoviews.org
- Altair: https://altair-viz.github.io/gallery/choropleth.html
- Plotly: https://plot.ly/python/#maps
- ...
另一个流行的在线地图的javascript库是 Leaflet.js ,这个库在 folium 和 ipyleaflet 包中有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