File:Pyramide des âges, Belgique. 2001-2013.svg

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search

Original file (SVG file, nominally 900 × 540 pixels, file size: 100 KB)

Captions

Captions

Add a one-line explanation of what this file represents

Summary

[edit]
Description
Français : Pyramides combinées des âges pour la Belgique en 2001 et 2013.
Date
Source Own work
Author Gvdmoort
SVG development
InfoField
 
The SVG code is valid.
 
This plot was created with Matplotlib.
Source code
InfoField

Python code

#!/usr/bin/env python3
# coding: utf-8
"""
Load population data from a json file and outputs a pyramid
of ages. 
Source: https://visuals.economie.fgov.be/visuals/data/population_age_gender.json
"""

import json
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter 
with open('population_age_gender.json') as data_file:
    json_data = json.load(data_file)

NIS = '01000'       # NIS code for country, see https://statbel.fgov.be/nl/open-data/refnis-code
w_color = '#ff9999' # color of bars for women
m_color = '#9999ff' # and for men

# build a dictionary: integer in [4,9,14..100] -> string as "0-4","5-9"..."100+"    
classes = dict()
for v in json_data['dimensions']['C']['values']:
    for w in v.items():
        classes[int(w[0])] = w[1]['FR']
# then a sorted list of the labels of age-classes as strings 
labels = [classes[k] for k in sorted(classes.keys())]

def getdata(json_data, NIS='01000', year = 2013):
    """
    returns a 21x2 array of integers representing the number of persons in
    each age-class, with men in 1rst column and women in 2d.
    """
    values = dict()
    for f in json_data['facts']:
        if f['g'] == NIS and f['y'] == year:
            if f['C'] in values:
                values[f['C']][f['s']] = f['M']
            else:
                values[f['C']] = {f['s']:f['M']}

    data = np.empty((len(values),3),dtype='int')
    i = 0
    for k in sorted(values.keys()):
        data[i] = [k,values[k]['M'],values[k]['F']]
        i += 1
    return data[:,1:3]

# function to assign positive values in X-axis
# https://matplotlib.org/devdocs/gallery/ticks_and_spines/tick_labels_from_values.html
def format_fn(tick_val, tick_pos):
    return int(abs(tick_val))

d_2001 = getdata(json_data,NIS,2001)
d_2013 = getdata(json_data,NIS,2013)

print('total hommes 2001:', np.sum(d_2001[:,0]))
print('total femmes 2001:', np.sum(d_2001[:,1]))
print('total 2001:', np.sum(d_2001[:,0:2])) 
print('total hommes 2013:', np.sum(d_2013[:,0]))
print('total femmes 2013:', np.sum(d_2013[:,1]))
print('total 2013:', np.sum(d_2013[:,0:2])) 

max_x = np.concatenate((d_2001,d_2013)).max() # used to get a symmetrical plot

fig, ax = plt.subplots(figsize=(10,6))

Xm_2013 = d_2013[:,0]  
Xw_2013 = d_2013[:,1]
Y = np.array(range(d_2013.shape[0]))

ax.barh(Y, -Xm_2013, color=m_color, align='center', label='Hommes 2013')
ax.barh(Y,  Xw_2013, color=w_color, align='center', label='Femmes 2013')

Xm_2001 = d_2001[:,0]
Xw_2001 = d_2001[:,1]

ax.set_xlim(-max_x*1.1,max_x*1.1) 
ax.step(-Xm_2001, Y-0.5, where='pre', color='#4444ff', label='Hommes 2001')
ax.step( Xw_2001, Y-0.5, where='pre', color='#ff4444', label='Femmes 2001')

ax.set_yticks(Y)
ax.set_yticklabels(labels)
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
ax.xaxis.set_major_locator(plt.MultipleLocator(100000))
ax.xaxis.set_minor_locator(plt.MultipleLocator(10000))
ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
ax.grid(axis='y', linewidth=0.25, linestyle='-', color='0.75')
plt.legend()
plt.title('Pyramide des âges, Belgique - 2001-2013')
plt.xlabel('Effectifs en unités')
plt.show()

Licensing

[edit]
I, the copyright holder of this work, hereby publish it under the following license:
w:en:Creative Commons
attribution share alike
This file is licensed under the Creative Commons Attribution-Share Alike 4.0 International license.
You are free:
  • to share – to copy, distribute and transmit the work
  • to remix – to adapt the work
Under the following conditions:
  • attribution – You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
  • share alike – If you remix, transform, or build upon the material, you must distribute your contributions under the same or compatible license as the original.

File history

Click on a date/time to view the file as it appeared at that time.

Date/TimeThumbnailDimensionsUserComment
current15:05, 10 February 2018Thumbnail for version as of 15:05, 10 February 2018900 × 540 (100 KB)Gvdmoort (talk | contribs)User created page with UploadWizard

There are no pages that use this file.

Metadata