Есть ли какой-нибудь более простой способ построить данные GeoPandas на диаграмме Альтаира?

Основной способ отображения GeoDataFrame в Altair:

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
)

Результат

Но он сломается, если я добавлю столбец с Nan или же DateTime ценности.

1 ответ

  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 gpdvega а также import gpdvega, altair будет работать с GeoDataFrame по-прежнему DataFrame, Подробности смотрите в документации

Другие вопросы по тегам