Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The basic way to display GeoDataFrame in 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
)

Result

But it will crush if I add column with Nan or DateTime values.

like image 533
ilia timofeev Avatar asked Nov 01 '25 16:11

ilia timofeev


1 Answers

  1. At first you can use world = alt.utils.sanitize_dataframe(world) to convert columns with JSON incompatible types.
  2. Or you can use gpdvega module to simplify code.
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
)

result

Just pip install gpdvega and import gpdvega. altair will work with GeoDataFrame as usual DataFrame. See details in documentation

like image 87
ilia timofeev Avatar answered Nov 04 '25 12:11

ilia timofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!