基于geopandas的精美地图绘制:geoplot

文摘   2024-10-01 12:35   北京  


基于geopandas的精美地图绘制:geoplot

个人信息

公众号:气python风雨

Image Name

关注我获取更多学习资料,第一时间收到我的Python学习资料,也可获取我的联系方式沟通合作

温馨提示

由于可视化代码过长隐藏,可点击运行Fork查看
若没有成功加载可视化图,点击运行可以查看
ps:隐藏代码在【代码已被隐藏】所在行,点击所在行,可以看到该行的最右角,会出现个三角形,点击查看即可

前言

项目目标

本项目旨在介绍geoplot的地图绘图示例。

项目方法

在以下内容中,将基于geoplot官方示例展示地图绘图。

安装与导入库

!pip install geoplot -i https://pypi.mirrors.ustc.edu.cn/simple/
Looking in indexes: https://pypi.mirrors.ustc.edu.cn/simple/
Collecting geoplot
  Downloading https://mirrors.ustc.edu.cn/pypi/packages/49/52/f7fa2faaead12a6a11d34d812a9615575e1fccb50cfe628e0d801cebe237/geoplot-0.5.1-py3-none-any.whl (28 kB)
Requirement already satisfied: cartopy in /opt/conda/lib/python3.9/site-packages (from geoplot) (0.23.0)
Requirement already satisfied: mapclassify>=2.1 in /opt/conda/lib/python3.9/site-packages (from geoplot) (2.5.0)
Requirement already satisfied: geopandas>=0.9.0 in /opt/conda/lib/python3.9/site-packages (from geoplot) (0.14.3)
Requirement already satisfied: seaborn in /opt/conda/lib/python3.9/site-packages (from geoplot) (0.11.2)
Collecting contextily>=1.0.0
  Downloading https://mirrors.ustc.edu.cn/pypi/packages/fb/46/07a029b73f9a5c7bbf9b538e6441c42014a448f335a1cc780616f2594bad/contextily-1.6.2-py3-none-any.whl (17 kB)
Requirement already satisfied: pandas in /opt/conda/lib/python3.9/site-packages (from geoplot) (2.0.3)
Requirement already satisfied: matplotlib>=3.1.2 in /opt/conda/lib/python3.9/site-packages (from geoplot) (3.8.3)
Requirement already satisfied: requests in /opt/conda/lib/python3.9/site-packages (from contextily>=1.0.0->geoplot) (2.27.1)
Requirement already satisfied: joblib in /opt/conda/lib/python3.9/site-packages (from contextily>=1.0.0->geoplot) (1.3.2)
Requirement already satisfied: xyzservices in /opt/conda/lib/python3.9/site-packages (from contextily>=1.0.0->geoplot) (2023.10.1)
Collecting mercantile
  Downloading https://mirrors.ustc.edu.cn/pypi/packages/b2/d6/de0cc74f8d36976aeca0dd2e9cbf711882ff8e177495115fd82459afdc4d/mercantile-1.2.1-py3-none-any.whl (14 kB)
Collecting geopy
  Downloading https://mirrors.ustc.edu.cn/pypi/packages/e5/15/cf2a69ade4b194aa524ac75112d5caac37414b20a3a03e6865dfe0bd1539/geopy-2.4.1-py3-none-any.whl (125 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m125.4/125.4 kB[0m [31m4.3 MB/s[0m eta [36m0:00:00[0m
[?25hRequirement already satisfied: pillow in /opt/conda/lib/python3.9/site-packages (from contextily>=1.0.0->geoplot) (9.4.0)
Requirement already satisfied: rasterio in /opt/conda/lib/python3.9/site-packages (from contextily>=1.0.0->geoplot) (1.3.6)
Requirement already satisfied: shapely>=1.8.0 in /opt/conda/lib/python3.9/site-packages (from geopandas>=0.9.0->geoplot) (1.8.5.post1)
Requirement already satisfied: pyproj>=3.3.0 in /opt/conda/lib/python3.9/site-packages (from geopandas>=0.9.0->geoplot) (3.4.1)
Requirement already satisfied: fiona>=1.8.21 in /opt/conda/lib/python3.9/site-packages (from geopandas>=0.9.0->geoplot) (1.9.1)
Requirement already satisfied: packaging in /opt/conda/lib/python3.9/site-packages (from geopandas>=0.9.0->geoplot) (23.2)
Requirement already satisfied: scikit-learn in /opt/conda/lib/python3.9/site-packages (from mapclassify>=2.1->geoplot) (0.24.2)
Requirement already satisfied: numpy>=1.3 in /opt/conda/lib/python3.9/site-packages (from mapclassify>=2.1->geoplot) (1.26.4)
Requirement already satisfied: networkx in /opt/conda/lib/python3.9/site-packages (from mapclassify>=2.1->geoplot) (2.8)
Requirement already satisfied: scipy>=1.0 in /opt/conda/lib/python3.9/site-packages (from mapclassify>=2.1->geoplot) (1.11.4)
Requirement already satisfied: cycler>=0.10 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (0.11.0)
Requirement already satisfied: importlib-resources>=3.2.0 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (5.7.1)
Requirement already satisfied: fonttools>=4.22.0 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (4.33.3)
Requirement already satisfied: contourpy>=1.0.1 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (1.2.0)
Requirement already satisfied: kiwisolver>=1.3.1 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (1.4.2)
Requirement already satisfied: python-dateutil>=2.7 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (2.8.2)
Requirement already satisfied: pyparsing>=2.3.1 in /opt/conda/lib/python3.9/site-packages (from matplotlib>=3.1.2->geoplot) (3.0.9)
Requirement already satisfied: tzdata>=2022.1 in /opt/conda/lib/python3.9/site-packages (from pandas->geoplot) (2024.1)
Requirement already satisfied: pytz>=2020.1 in /opt/conda/lib/python3.9/site-packages (from pandas->geoplot) (2022.1)
Requirement already satisfied: pyshp>=2.3 in /opt/conda/lib/python3.9/site-packages (from cartopy->geoplot) (2.3.1)
Requirement already satisfied: cligj>=0.5 in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (0.7.2)
Requirement already satisfied: certifi in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (2024.2.2)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (62.2.0)
Requirement already satisfied: attrs>=19.2.0 in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (21.4.0)
Requirement already satisfied: click-plugins>=1.0 in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (1.1.1)
Requirement already satisfied: munch>=2.3.2 in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (4.0.0)
Requirement already satisfied: click~=8.0 in /opt/conda/lib/python3.9/site-packages (from fiona>=1.8.21->geopandas>=0.9.0->geoplot) (8.1.3)
Requirement already satisfied: zipp>=3.1.0 in /opt/conda/lib/python3.9/site-packages (from importlib-resources>=3.2.0->matplotlib>=3.1.2->geoplot) (3.8.0)
Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.9/site-packages (from python-dateutil>=2.7->matplotlib>=3.1.2->geoplot) (1.16.0)
Collecting geographiclib<3,>=1.52
  Downloading https://mirrors.ustc.edu.cn/pypi/packages/9f/5a/a26132406f1f40cf51ea349a5f11b0a46cec02a2031ff82e391c2537247a/geographiclib-2.0-py3-none-any.whl (40 kB)
[2K     [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m40.3/40.3 kB[0m [31m14.4 MB/s[0m eta [36m0:00:00[0m
[?25hRequirement already satisfied: snuggs>=1.4.1 in /opt/conda/lib/python3.9/site-packages (from rasterio->contextily>=1.0.0->geoplot) (1.4.7)
Requirement already satisfied: affine in /opt/conda/lib/python3.9/site-packages (from rasterio->contextily>=1.0.0->geoplot) (2.4.0)
Requirement already satisfied: charset-normalizer~=2.0.0 in /opt/conda/lib/python3.9/site-packages (from requests->contextily>=1.0.0->geoplot) (2.0.12)
Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.9/site-packages (from requests->contextily>=1.0.0->geoplot) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/conda/lib/python3.9/site-packages (from requests->contextily>=1.0.0->geoplot) (1.26.9)
Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.9/site-packages (from scikit-learn->mapclassify>=2.1->geoplot) (3.1.0)
Installing collected packages: mercantile, geographiclib, geopy, contextily, geoplot
Successfully installed contextily-1.6.2 geographiclib-2.0 geoplot-0.5.1 geopy-2.4.1 mercantile-1.2.1
import geopandas as gpd
import geoplot as gplt
usa_cities = gpd.read_file(gplt.datasets.get_path('usa_cities'))
usa_cities.head()



idPOP_2010ELEV_IN_FTSTATEgeometry
05340888.01611.0NDPOINT (-101.29627 48.23251)
110152838.0830.0NDPOINT (-97.03285 47.92526)
215315427.01407.0NDPOINT (-98.70844 46.91054)
3177105549.0902.0NDPOINT (-96.78980 46.87719)
419217787.02411.0NDPOINT (-102.78962 46.87918)
continental_usa_cities = usa_cities.query('STATE not in ["HI", "AK", "PR"]')
gplt.pointplot(continental_usa_cities)
<Axes: >

contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
gplt.polyplot(contiguous_usa)
<Axes: >

ax = gplt.polyplot(contiguous_usa)
gplt.pointplot(continental_usa_cities, ax=ax)
<Axes: >

import geoplot.crs as gcrs

ax = gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea())
gplt.pointplot(continental_usa_cities, ax=ax)
<GeoAxes: >

ax = gplt.polyplot(
    contiguous_usa, projection=gcrs.AlbersEqualArea(),
    edgecolor='white', facecolor='lightgray',
    figsize=(128)
)
gplt.pointplot(
    continental_usa_cities, ax=ax, hue='ELEV_IN_FT', cmap='Blues',
    scheme='quantiles',
    scale='ELEV_IN_FT', limits=(110),
    legend=True, legend_var='scale',
    legend_kwargs={'frameon'False},
    legend_values=[-1101750360055007400],
    legend_labels=['-110 feet''1750 feet''3600 feet''5500 feet''7400 feet']
)
ax.set_title('Cities in the Continental United States by Elevation', fontsize=16)
Text(0.5, 1.0, 'Cities in the Continental United States by Elevation')

gplt.choropleth(
    contiguous_usa, hue='population', projection=gcrs.AlbersEqualArea(),
    edgecolor='white', linewidth=1,
    cmap='Greens', legend=True,
    scheme='FisherJenks',
    legend_labels=[
        '<3 million''3-6.7 million''6.7-12.8 million',
        '12.8-25 million''25-37 million'
    ]
)
<GeoAxes: >

import geoplot.crs as gcrs
import matplotlib.pyplot as plt
import mapclassify as mc

scheme = mc.Quantiles(continental_usa_cities['POP_2010'], k=5)
proj = gcrs.AlbersEqualArea()

ax = gplt.polyplot(
    contiguous_usa,
    zorder=-1,
    linewidth=1,
    projection=proj,
    edgecolor='white',
    facecolor='lightgray',
    figsize=(1212)
)

gplt.pointplot(
    continental_usa_cities,
    scale='POP_2010',
    limits=(230),
    hue='POP_2010',
    cmap='Blues',
    scheme=scheme,
    legend=True,
    legend_var='scale',
    legend_values=[800000020000001000000100000],
    legend_labels=['8 million''2 million''1 million''100 thousand'],
    legend_kwargs={'frameon'False'loc''lower right'},
    ax=ax
)

plt.title("Cities in the contiguous United States, 2010")
Text(0.5, 1.0, 'Cities in the contiguous United States, 2010')

import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt

dc_roads = gpd.read_file(gplt.datasets.get_path('dc_roads'))

gplt.sankey(
    dc_roads, projection=gcrs.AlbersEqualArea(),
    scale='aadt', limits=(0.110), color='black'
)

plt.title("Streets in Washington DC by Average Daily Traffic, 2015")
Text(0.5, 1.0, 'Streets in Washington DC by Average Daily Traffic, 2015')

import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt

# load the data
nyc_boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs'))
tickets = gpd.read_file(gplt.datasets.get_path('nyc_parking_tickets'))

proj = gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059)


def plot_state_to_ax(state, ax):
    gplt.choropleth(
        tickets.set_index('id').loc[:, [state, 'geometry']],
        hue=state, cmap='Blues',
        linewidth=0.0, ax=ax
    )
    gplt.polyplot(
        nyc_boroughs, edgecolor='black', linewidth=0.5, ax=ax
    )


f, axarr = plt.subplots(22, figsize=(1213), subplot_kw={'projection': proj})

plt.suptitle('Parking Tickets Issued to State by Precinct, 2016', fontsize=16)
plt.subplots_adjust(top=0.95)

plot_state_to_ax('ny', axarr[0][0])
axarr[0][0].set_title('New York (n=6,679,268)')

plot_state_to_ax('nj', axarr[0][1])
axarr[0][1].set_title('New Jersey (n=854,647)')

plot_state_to_ax('pa', axarr[1][0])
axarr[1][0].set_title('Pennsylvania (n=215,065)')

plot_state_to_ax('ct', axarr[1][1])
axarr[1][1].set_title('Connecticut (n=126,661)')
Text(0.5, 1.0, 'Connecticut (n=126,661)')

import pandas as pd
import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt
import mapclassify as mc

# load the data
obesity_by_state = pd.read_csv(gplt.datasets.get_path('obesity_by_state'), sep='\t')
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
contiguous_usa['Obesity Rate'] = contiguous_usa['state'].map(
    lambda state: obesity_by_state.query("State == @state").iloc[0]['Percent']
)
scheme = mc.Quantiles(contiguous_usa['Obesity Rate'], k=5)


ax = gplt.cartogram(
    contiguous_usa,
    scale='Obesity Rate', limits=(0.751),
    projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5),
    hue='Obesity Rate', cmap='Reds', scheme=scheme,
    linewidth=0.5,
    legend=True, legend_kwargs={'loc''lower right'}, legend_var='hue',
    figsize=(127)
)
gplt.polyplot(contiguous_usa, facecolor='lightgray', edgecolor='None', ax=ax)

plt.title("Adult Obesity Rate by State, 2013")
Text(0.5, 1.0, 'Adult Obesity Rate by State, 2013')

小结

虽然许久不更新,但geoplot依然能绘制颜值在线的地图,当然还有更多功能有待发掘

气python风雨
主要发一些涉及大气科学的Python文章与个人学习备忘录
 最新文章