1

试图用简单的数字数据渲染美国县地图。此代码无法呈现几种状态:

from urllib.request import urlopen
import json
import requests
import os
import pandas as pd
import plotly.express as px

with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

tsfile = 'time_series_covid19_confirmed_US.csv'
tsurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/' + tsfile

if not os.path.exists(tsfile):
    req = requests.get(tsurl)
    with open(tsfile, 'wb') as f:
        f.write(req.content)
ts = pd.read_csv(tsfile)

ts.dropna(inplace=True)
ts = ts[ts['FIPS'] < 80000].copy(deep=True)

ts_short = ts[['FIPS', '5/9/20', '5/10/20']].copy(deep=True)
ts_short['delta'] = ts_short['5/10/20'] - ts_short['5/9/20']
ts_short = ts_short[ts_short['delta'] >= 0].copy(deep=True)
dmin = ts_short['5/10/20'].min()
dmax = ts_short['5/10/20'].max()

fig = px.choropleth(ts_short, geojson=counties, locations='FIPS', color='5/10/20',
                           color_continuous_scale="Viridis",
                           range_color=(dmin, dmax),
                           scope="usa"
                          )

fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig.show()

这就是渲染的内容(无论如何颜色似乎都是错误的):

在此处输入图像描述

但是,替代方法 create_choropleth() 可以很好地处理相同的数据:

import plotly.figure_factory as pff
fig2 = pff.create_choropleth(fips=ts_short['FIPS'], values=ts_short['5/10/20'])
fig2.show()

在此处输入图像描述

如何对 choropleth() 进行故障排除?

情节 4.6.0

Python 3.7.7

Jupyter 笔记本

蟒蛇

视窗

4

1 回答 1

2

您需要将 FIPS 值从整数转换为 5 位字符串值。那些缺失的包括来自加利福尼亚的县,应该以'01'开头,科罗拉多州,以'08'开头,等等。

于 2020-10-18T00:39:55.430 回答