我正在尝试使用csv (wb_hiv_prevalence_csv_file)在侏儒地图上绘制艾滋病流行情况,以便进行数据可视化。当我打印相关数据(例如hiv_d_2018、country_name等)时,代码的其他方面可以正常工作。然而,当我创建svg文件时,经过所有的努力,映射仍然是空白的,没有通常的彩色数据可视化。请帮助我知道我哪里搞错了。谢谢。
处理数据和创建地图的代码。
import csv
import pygal.maps.world
from country_codes import get_country_code
# Get the country names, country codes and HIV data from file.
filename = 'wb_hiv_prevalence.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
country_names, hiv_data_2018 = [], []
for row in reader:
country_name = (row[0])
hiv_d_2018 = (row[62])
country_names.append(country_name)
hiv_data_2018.append(hiv_d_2018)
#print(country_name)
#print(hiv_data_2018)
code = get_country_code(country_name)
if code and hiv_d_2018 != '':
cc_hiv = code + ': ' + str(hiv_d_2018) + ': ' + country_name
#print(cc_hiv)
elif code and hiv_d_2018 == '':
cc_zero_hiv = code + ': Zero Hiv Prevalence- ' + country_name
#print(cc_zero_hiv)
else:
error = 'ERROR - ' + country_name
#print(error)
#print(hiv_d_2018)
wm = pygal.maps.world.World()
wm.title = 'World HIV prevalence rates in 2018, by Country'
wm.add('HIV prevalence rate 0-24%', hiv_d_2018)
wm.render_to_file('wb_hiv_prevalence.svg')从pygal模块获取国家代码的代码。
from pygal.maps.world import COUNTRIES
from pygal_maps_world import i18n
def get_country_code(country_name):
"""Return the Pygal 2-digit country code for the given country."""
for code, name in COUNTRIES.items():
if name == country_name:
return code
# If the country was not found, return None.
return None

发布于 2021-01-21 07:32:14
您必须创建字典并将其传递给wm.add函数。由于在CSV文件或'‘中有一些没有值的数据,标准的浮点数转换将抛出一个error.You,排除if条件中的那些值,并将字符串转换为浮点数(Hiv_d_2018)
import csv
import pygal.maps.world
from country_codes import get_country_code
# Get the country names, country codes and HIV data from file.
filename = 'wb_hiv_prevalence.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
new_dict1={}
country_names, hiv_data_2018 = [], []
for row in reader:
country_name = (row[0])
code = get_country_code(country_name)
hiv_d_2018 = (row[62])
country_names.append(country_name)
hiv_data_2018.append(hiv_d_2018)
if code and hiv_d_2018 != '':
new_dict[code]=float(hiv_d_2018)
else:
error = 'ERROR - ' + country_name
#print(error)
#print(hiv_d_2018)
wm = pygal.maps.world.World()
wm.title = 'World HIV prevalence rates in 2018, by Country'
wm.add('HIV prevalence rate 0-24%', new_dict)
wm.render_to_file('wb_hiv_prevalence.svg')https://stackoverflow.com/questions/59096274
复制相似问题