python - 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
)
结果
解决方案
使用时图表为空的原因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'
)
推荐阅读
- bash - 如何在本地运行 go 二进制文件作为 Jenkins 管道的最后阶段?
- java - 如何通过命令行在不同的jdks/jre上编译和运行java程序?
- html - 为什么我的 html 页面没有下载这些文件?
- python-3.x - 带有IDE Microsoft Code的python中的configparser()问题
- javascript - 基于队列更新对象值
- python - 使用链式分配遍历链表
- reactjs - React:防止多次onClick()引起的双重提交的正确模式是什么?
- c# - 需要帮助调整使用 Azure AD 的 ASP.NET 以允许来自第三方的 SSO
- javascript - 如何使用 location.href 下载 dmg 文件
- python - Pandas - 对包含间隔的 MultiIndex 进行索引