Altair choropleth——将与每个县关联的值添加到地图

Altair choropleth -- adding values associated with each County to the map

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

数据框-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
)

结果

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

此外,如果将您的 topojson 与 what is in the vega sample data (for easier comparison paste them into a json viewer) you can see that the key used in the sample data file for the lookup example (id) is at the top level of each geometry object while in your fie it is nested one more level under properties. This means that you need to use 'properties.NAME' as the lookup string ( 进行比较):

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'
)