注意
This page was generated from docs/user_guide/interactive_mapping.ipynb.
交互式地图#
除了静态图表,geopandas
可以基于 folium 库创建交互式地图。
创建用于交互式探索的地图与GeoSeries或GeoDataFrame的explore()方法中的静态plots的API相似。
加载一些示例数据:
[1]:
import geopandas
import geodatasets
nybb = geopandas.read_file(geodatasets.get_path("nybb"))
chicago = geopandas.read_file(geodatasets.get_path("geoda.chicago_commpop"))
groceries = geopandas.read_file(geodatasets.get_path("geoda.groceries")).explode(ignore_index=True)
最简单的选项是使用 GeoDataFrame.explore()
:
[2]:
nybb.explore()
[2]:
Make this Notebook Trusted to load map: File -> Trust Notebook
交互式绘图在定制方面提供了与静态绘图大致相同的功能,还增加了一些额外的特性。请查看下面的代码,它绘制了一个自定义的地理数据色块地图。您可以使用 "BoroName"
列,作为地理数据色块的输入,鼠标悬停时仅显示其名称,但点击时显示所有值。您还可以传递自定义背景图块(可以是 folium 支持的名称、被 xyzservices.providers.query_name()
识别的名称、XYZ URL 或者 xyzservices.TileProvider
对象),指定颜色映射(由 matplotlib
支持的所有选项)并指定黑色轮廓。
注意
请注意,如果您想使用背景图块,GeoDataFrame 需要设置一个 CRS。
[3]:
nybb.explore(
column="BoroName", # make choropleth based on "BoroName" column
tooltip="BoroName", # show "BoroName" value in tooltip (on hover)
popup=True, # show all values in popup (on click)
tiles="CartoDB positron", # use "CartoDB positron" tiles
cmap="Set1", # use "Set1" matplotlib colormap
style_kwds=dict(color="black"), # use black outline
)
[3]:
Make this Notebook Trusted to load map: File -> Trust Notebook
The explore()
方法返回一个 folium.Map
对象,该对象也可以直接传递(就像您在 plot()
中对 ax
所做的那样)。然后,您可以直接在结果地图上使用 folium 功能。在下面的示例中,您可以在同一地图上绘制两个 GeoDataFrames,并使用 folium 添加图层控制。您还可以添加额外的图块,使您能够直接在地图中更改背景。
[4]:
import folium
m = chicago.explore(
column="POP2010", # make choropleth based on "POP2010" column
scheme="naturalbreaks", # use mapclassify's natural breaks scheme
legend=True, # show legend
k=10, # use 10 bins
tooltip=False, # hide tooltip
popup=["POP2010", "POP2000"], # show popup (on-click)
legend_kwds=dict(colorbar=False), # do not use colorbar
name="chicago", # name of the layer in the map
)
groceries.explore(
m=m, # pass the map object
color="red", # use red color on all points
marker_kwds=dict(radius=5, fill=True), # make marker radius 10px with fill
tooltip="Address", # show "name" column in the tooltip
tooltip_kwds=dict(labels=False), # do not show column label in the tooltip
name="groceries", # name of the layer in the map
)
folium.TileLayer("CartoDB positron", show=False).add_to(
m
) # use folium to add alternative tiles
folium.LayerControl().add_to(m) # use folium to add layer control
m # show map
[4]:
Make this Notebook Trusted to load map: File -> Trust Notebook