繁体   English   中英

如何使用 Pygal 和 Python 在世界地图中显示字符串数据?

[英]How do I display string data in a world map using Pygal and Python?

所以我正在阅读 Python Crash Course 这本书,其中一个练习是找到一个自定义的 CSV 文件并使用 Pygal 将其数据输出到世界地图中。 在过去的练习中,我们在地图中显示数字,但现在我尝试显示字符串,每个字符串都称为“高收入”、“低收入”等等。 到目前为止,我有这个代码:

import csv
import pygal
from pygal.maps.world import World
from country_codes import get_country_code

# Loading data
filename = 'metadata_country.csv'
with open(filename) as f:
    children_list = csv.reader(f)
    header_row = next(children_list)    

    incomes = {}
    for data in children_list:
        try:
            country_code = get_country_code(data[4])
            child_income = data[2]
        except ValueError:
            print("Data missing for " + country_code)
        else:
            incomes[country_code] = child_income


income_levels = ['High income', 'Lower middle income', 'Upper Middle income', 'Low income']

# Filtering the child incomes dictionary   
children_high, children_upper_middle, children_lower_middle, children_low = {}, {}, {}, {}
for country, income in incomes.items():
    if income == income_levels[0]:
        children_high[country] = income
    elif income == income_levels[1]:
        children_lower_middle[country] = income
    elif income == income_levels[2]:
        children_upper_middle[country] = income
    else:
        children_low[country] = income

world_map = World()
world_map.title = 'Children income per country'
world_map.add('High income', children_high)
world_map.add('Upper Middle income', children_upper_middle)
world_map.add('Lower middle income', children_lower_middle)
world_map.add('Low income', children_low)

world_map.render_to_file('children_income.svg')

但我收到以下错误:

  File "C:\Users\Matheus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\map.py", line 83, in _plot      
    ratio = .3 + .7 * (value - min_) / (max_ - min_)
TypeError: unsupported operand type(s) for -: 'str' and 'str'

有人可以帮我解决它的问题吗? 我是 Python 新手,也是 Pygal 新手。 只是为了好奇而这样做。 谢谢! 如果需要,链接到 .csv 文件。

解决了:

实际上,更改此部分可以解决问题:

# Filtering the child incomes dictionary   
children_high, children_upper_middle, children_lower_middle, children_low = {}, {}, {}, {}
for country, income in incomes.items():    
    if income == income_levels[0]:
        children_high[country] = income_levels[0]
    elif income == income_levels[1]:
        children_lower_middle[country] = income_levels[1]
    elif income == income_levels[2]:
        children_upper_middle[country] = income_levels[2]
    else:
        children_low[country] = income_levels[3]

我之前使用了字典“收入”中的“收入”值,但由于某种原因它不起作用。 现在我将值作为 'income_levels[index]' 传递,它返回一个字符串,它按预期工作。 如果有人能查明造成这种情况的原因,我仍然会很感激。 谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM