Search code examples
pythonnumber-formattingpygal

When using pygal.maps.world is there a way to format the numbers that display a country's population?


I am using pygal to make an interactive map showing world country populations from 2010. I am trying to find a way so that the populations of the country display with commas inserted ie as 10,000 not simply 10000.

What my map currently looks like; you can see how hard the populations are to read.

I have already tried using "{:,}".format(x) when reading the numbers into my lists for the different population levels, but it causes an error. I believe this to be because this changes the value to a string.

I also tried inserting a piece of code I found online

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

This doesn't cause any errors but doesn't fix how the numbers are formatted either. I am hoping someone might know of a built in function such as:

wm_style = RotateStyle('#336699')

Which is letting me set a color scheme.

Below is a the part of my code which is plotting the map.

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')

Solution

  • Setting the value_formatter property will change the label format, but in your code you recreate the World object after setting the property. This newly created object will have the default value formatter. You can also remove one of the lines setting the value_formatter property as they both achieve the same thing.

    Re-ordering the code will fix your problem:

    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')