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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章