首页 > 解决方案 > Altair choropleth - 将与每个县相关联的值添加到地图

问题描述

我正在尝试将与每个县相关联的 pop_april_2010 值添加到地图中。但是,当我不包含“color='pop_april_2010:Q'”行时,我的代码仅返回基本地图。包含该线会导致没有地图的空图像。

数据框 - df
数据来自 Kaggle > https://www.kaggle.com/camnugent/california-housing-feature-engineering?select=cal_populations_county.csv

在此处输入图像描述

代码

url = 'https://raw.githubusercontent.com/deldersveld/topojson/master/countries/us-states/CA-06-california-counties.json'

source = alt.topo_feature(url, "cb_2015_california_county_20m")

alt.Chart(source).mark_geoshape().encode(
tooltip='properties.NAME:N',
# color='pop_april_2010:Q'
).transform_lookup(
    lookup='County',
    from_= alt.LookupData(cal2, 'County', ['pop_april_2010']),
).properties(
    width=500,
    height=300
).project(
    type='albersUsa'
).properties(
    width=500,
    height=300
)

结果

在此处输入图像描述

标签: pythonaltair

解决方案


使用时图表为空的原因color是在查找 topojson 文件时使用了错误的列名,因此没有返回任何内容,并且您将引用不存在列的字符串传递给color. 如果您检查您的 topojson 文件,您可以看到每个县的名称都存储在NAME属性中,而不是County.

此外,如果您将您的 topojson与 vega 示例数据中的内容进行比较(为了便于比较,请将它们粘贴到 json 查看器中),您可以看到用于查找示例 ( id) 的示例数据文件中的键位于顶层geometry在您的 fie 中的每个对象都嵌套在properties. 这意味着您需要'properties.NAME'用作查找字符串(有关此答案中工作地理数据的更多详细信息):

import altair as alt
import pandas as pd

# From https://www.kaggle.com/camnugent/california-housing-feature-engineering?select=cal_populations_county.csv
cal2 = pd.read_csv('~/Downloads/cal_populations_county.csv')

url = 'https://raw.githubusercontent.com/deldersveld/topojson/master/countries/us-states/CA-06-california-counties.json'
source = alt.topo_feature(url, "cb_2015_california_county_20m")

alt.Chart(source).mark_geoshape().encode(
    tooltip='properties.NAME:N',
    color='pop_april_2010:Q'
).transform_lookup(
    lookup='properties.NAME',
    from_= alt.LookupData(cal2, 'County', ['pop_april_2010']),
).properties(
    width=500,
    height=300
).project(
    type='albersUsa'
)

在此处输入图像描述


推荐阅读