在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
值的列,它会崩溃。
答案 0 :(得分:2)
world = alt.utils.sanitize_dataframe(world)
来转换JSON不兼容类型的列。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
使用。查看documentation