【发布时间】:2021-12-31 21:00:41
【问题描述】:
我有美国几个州的数据,而其他州的数据为空。在创建地图时,我想在文本中缺失值的状态中添加阴影,但我正在努力寻找正确的方法。使用我当前的代码,我无法获取整个美国地图,包括具有 Null 值的州,并且只会弹出具有特定分配值的州。我还查看了之前发布的问题并尝试对地图进行分层,但这给了我一个错误。 here's how cc_df looks like
这是我的代码:
# import the required library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt# import seaborn library
%matplotlib inline
import altair as alt
from vega_datasets import data
# State database
states_df = pd.read_csv(
'https://www2.census.gov/geo/docs/reference/state.txt',
# pipe seperated file
sep="|",
# FIPS are best as strings
dtype='str',
# rename columns
header=0, names=['state_fips', 'state', 'state_name', 'StateENS'],
# drop last column
usecols=['state_fips', 'state_name', 'state']
).set_index('state')
states_df['id'] = states_df['state_fips'].astype(int)
# The data to map
cc_df = pd.read_csv('hv_cwad.csv',
usecols=['state', 'CWAD'])
cc_df = cc_df.groupby('state').mean()
# Combine state database and our own data
#cc_state_df = pd.merge(cc_df, states_df)
cc_state_df = states_df.join(cc_df).reset_index()
# %%
# Create the map
states = alt.topo_feature(data.us_10m.url, 'states')
variable_list = ['CWAD']
alt.Chart(states).mark_geoshape(stroke='lightgrey',
strokeWidth=.5).encode(
alt.Color(alt.repeat('row'), type='quantitative')
).transform_lookup(
lookup='id',
from_=alt.LookupData(cc_state_df, 'id', variable_list)
).properties(
width=300,
height=300
).project(
type='albersUsa'
).repeat(
row=variable_list
).resolve_scale(
color='independent'
)
输出如下所示:
【问题讨论】:
-
我也尝试过将两张地图分层。这就是代码的样子 #Adding an outline to the map outline = alt.Chart(states).mark_geoshape(stroke='black').project( type='albersUsa' ).properties( #width=700, #height=400 ) alt.layer(plot,outline) 但这给了我一个 ValueError: Repeat charts cannot be layered
-
我认为您可以重复分层图表(其他方式)。我试图复制+粘贴你的代码,但我得到了
FileNotFoundError: [Errno 2] No such file or directory: 'hv_cwad.csv。 -
Mattjin,我添加了数据框 (cc_df) 的快照。我认为我们不能在此处添加 csv 文件。您能否澄清一下“其他方式”的含义?
-
我运行了您的代码并确认未显示 NA 状态。当我将缺失的数据值更新为 0 时,所有状态都显示出来了。如果这是您想要的,我会回复。
-
@r-beginners 是的,拜托。谢谢你。正如您在输出图中看到的那样,只有带有数据的状态看起来很奇怪。我试图以灰色添加没有数据的州,或者至少是缺少数据的州的轮廓。
标签: python plotly data-visualization altair choropleth