首页 > 解决方案 > 使用 pygal.maps.world 时,有没有办法格式化显示一个国家人口的数字?

问题描述

我正在使用 pygal 制作一张显示 2010 年以来世界国家人口的交互式地图。我试图找到一种方法,使该国家的人口显示为插入逗号,即 10,000 而不仅仅是 10000。

我的地图目前的样子; 你可以看到人口是多么难以阅读。

在将不同人口水平的数字读入我的列表时,我已经尝试使用 "{:,}".format(x) ,但这会导致错误。我相信这是因为这会将值更改为字符串。

我还尝试插入我在网上找到的一段代码

 wm.value_formatter = lambda x: "{:,}".format(x).

这不会导致任何错误,但也不会修复数字的格式。我希望有人可能知道内置功能,例如:

wm_style = RotateStyle('#336699')

这让我设置了一个配色方案。

下面是我的代码的一部分,它正在绘制地图。

wm = World()

wm.force_uri_protocol = "http"

wm_style = RotateStyle('#996699')
wm.value_formatter = lambda x: "{:,}".format(x)
wm.value_formatter = lambda y: "{:,}".format(y)
wm = World(style=wm_style)

wm.title = "Country populations year 2010"
wm.add('0-10 million', cc_pop_low)
wm.add("10m to 1 billion", cc_pop_mid)
wm.add('Over 1 billion', cc_pop_high)

wm.render_to_file('world_population.svg')

标签: pythonnumber-formattingpygal

解决方案


设置value_formatter属性将更改标签格式,但在您的代码中,您World在设置属性后重新创建对象。这个新创建的对象将具有默认值格式化程序。您还可以删除设置value_formatter属性的行之一,因为它们都实现了相同的目标。

重新排序代码将解决您的问题:

wm_style = RotateStyle('#996699')
wm = World(style=wm_style)
wm.value_formatter = lambda x: "{:,}".format(x)
wm.force_uri_protocol = "http"

wm.title = "Country populations year 2010"
wm.add('0-10 million', cc_pop_low)
wm.add("10m to 1 billion", cc_pop_mid)
wm.add('Over 1 billion', cc_pop_high)

wm.render_to_file('world_population.svg')

推荐阅读