在 Altair 图表中绘制 GeoPandas 数据是否有更简单的方法?

Is any simpler way to plot GeoPandas data in Altair chart?

Altair中显示GeoDataFrame的基本方式:

import altair as alt
import geopandas as gpd

alt.renderers.enable('notebook')

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

data  = alt.InlineData(values = world[world.continent=='Africa'].__geo_interface__, #geopandas to geojson
                       # root object type is "FeatureCollection" but we need its features
                       format = alt.DataFormat(property='features',type='json')) 
alt.Chart(data).mark_geoshape(
).encode( 
    color='properties.pop_est:Q', # GeoDataFrame fields are accessible through a "properties" object 
    tooltip=['properties.name:N','properties.pop_est:Q']
).properties( 

    width=500,
    height=300
)

但是如果我添加具有 NanDateTime 值的列,它会崩溃。

  1. 首先,您可以使用 world = alt.utils.sanitize_dataframe(world) 转换具有 JSON 不兼容类型的列。
  2. 或者您可以使用 gpdvega 模块来简化代码。
import altair as alt
import geopandas as gpd
import gpdvega 

alt.renderers.enable('notebook')

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

alt.Chart(world[world.continent=='Africa']).mark_geoshape(
).encode( 
    color='pop_est', 
    tooltip=['name','pop_est']
).properties( 
    width=500,
    height=300
)

只是 pip install gpdvegaimport gpdvegaaltair 将像往常一样与 GeoDataFrame 一起工作 DataFrame。请参阅 documentation

中的详细信息