admin管理员组

文章数量:1487745

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

温馨提示

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

前言

项目目标

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

项目方法

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

安装与导入库

代码语言:javascript代码运行次数:0运行复制
!pip install geoplot -i /
代码语言:javascript代码运行次数:0运行复制
Looking in indexes: /
Collecting geoplot
  Downloading .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 .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 .2.1-py3-none-any.whl (14 kB)
Collecting geopy
  Downloading .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 .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
代码语言:javascript代码运行次数:0运行复制
import geopandas as gpd
import geoplot as gplt
usa_cities = gpd.read_file(gplt.datasets.get_path('usa_cities'))
usa_cities.head()

id

POP_2010

ELEV_IN_FT

STATE

geometry

0

53

40888.0

1611.0

ND

POINT (-101.29627 48.23251)

1

101

52838.0

830.0

ND

POINT (-97.03285 47.92526)

2

153

15427.0

1407.0

ND

POINT (-98.70844 46.91054)

3

177

105549.0

902.0

ND

POINT (-96.78980 46.87719)

4

192

17787.0

2411.0

ND

POINT (-102.78962 46.87918)

代码语言:javascript代码运行次数:0运行复制
continental_usa_cities = usa_cities.query('STATE not in ["HI", "AK", "PR"]')
gplt.pointplot(continental_usa_cities)
代码语言:javascript代码运行次数:0运行复制
<Axes: >
代码语言:javascript代码运行次数:0运行复制
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
gplt.polyplot(contiguous_usa)
代码语言:javascript代码运行次数:0运行复制
<Axes: >
代码语言:javascript代码运行次数:0运行复制
ax = gplt.polyplot(contiguous_usa)
gplt.pointplot(continental_usa_cities, ax=ax)
代码语言:javascript代码运行次数:0运行复制
<Axes: >
代码语言:javascript代码运行次数:0运行复制
import geoplot.crs as gcrs

ax = gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea())
gplt.pointplot(continental_usa_cities, ax=ax)
代码语言:javascript代码运行次数:0运行复制
<GeoAxes: >
代码语言:javascript代码运行次数:0运行复制
ax = gplt.polyplot(
    contiguous_usa, projection=gcrs.AlbersEqualArea(),
    edgecolor='white', facecolor='lightgray',
    figsize=(12, 8)
)
gplt.pointplot(
    continental_usa_cities, ax=ax, hue='ELEV_IN_FT', cmap='Blues',
    scheme='quantiles',
    scale='ELEV_IN_FT', limits=(1, 10),
    legend=True, legend_var='scale',
    legend_kwargs={'frameon': False},
    legend_values=[-110, 1750, 3600, 5500, 7400],
    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)
代码语言:javascript代码运行次数:0运行复制
Text(0.5, 1.0, 'Cities in the Continental United States by Elevation')
代码语言:javascript代码运行次数:0运行复制
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'
    ]
)
代码语言:javascript代码运行次数:0运行复制
<GeoAxes: >
代码语言:javascript代码运行次数:0运行复制
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=(12, 12)
)

gplt.pointplot(
    continental_usa_cities,
    scale='POP_2010',
    limits=(2, 30),
    hue='POP_2010',
    cmap='Blues',
    scheme=scheme,
    legend=True,
    legend_var='scale',
    legend_values=[8000000, 2000000, 1000000, 100000],
    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")
代码语言:javascript代码运行次数:0运行复制
Text(0.5, 1.0, 'Cities in the contiguous United States, 2010')
代码语言:javascript代码运行次数:0运行复制
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.1, 10), color='black'
)

plt.title("Streets in Washington DC by Average Daily Traffic, 2015")
代码语言:javascript代码运行次数:0运行复制
Text(0.5, 1.0, 'Streets in Washington DC by Average Daily Traffic, 2015')
代码语言:javascript代码运行次数:0运行复制
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(2, 2, figsize=(12, 13), 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)')
代码语言:javascript代码运行次数:0运行复制
Text(0.5, 1.0, 'Connecticut (n=126,661)')
代码语言:javascript代码运行次数:0运行复制
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.75, 1),
    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=(12, 7)
)
gplt.polyplot(contiguous_usa, facecolor='lightgray', edgecolor='None', ax=ax)

plt.title("Adult Obesity Rate by State, 2013")
代码语言:javascript代码运行次数:0运行复制
Text(0.5, 1.0, 'Adult Obesity Rate by State, 2013')

小结

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2024-10-01,如有侵权请联系 cloudcommunity@tencent 删除地图condageopandasimportpython3

本文标签: 基于geopandas的精美地图绘制geoplot