Life Expectancy by sex between 2000 and 2021 in Kenya (WHO)
Plot showing the life expectancy using data from the World Health Organization (WHO) between 2000 and 2021 in Kenya.
data-science
Author
Kabui, Charles
Published
10 March 2025
Keywords
kenya, population, year-2000, year-2021, life-expectancy, WHO
Imports
Code
import pandas as pdimport urllib.parseimport matplotlib.pyplot as pltimport seaborn as snsdef plot_who_data( raw_data: pd.DataFrame, title: str, year_col ="Year", value_col ="Value", pivot_columns ="Sex", pivot_data_columns = [ {"name": "TOTAL","options": {'marker': 'o','linewidth': 2,'color': 'purple' } }, {"name": "MALE","options": {'marker': 's','linewidth': 2,'color': 'blue' } }, {"name": "FEMALE","options": {'marker': '^','linewidth': 2,'color': 'pink' } }, ]): data = raw_data.copy()# Convert Year to numeric and Value to float data[year_col] = pd.to_numeric(data[year_col]) data[value_col] = pd.to_numeric(data[value_col])# Pivot the data to have columns for each sex category pivot_data = data.pivot_table(index=year_col, columns=pivot_columns, values=value_col)# Set the style sns.set_style("whitegrid") fig, ax = plt.subplots(figsize=(12, 6))# Plot the datafor column in pivot_data_columns: sex = column['name'] ax.plot(pivot_data.index, pivot_data[sex], label=sex, **column['options'])# Add title and labels ax.set_title(title, fontsize=16) ax.set_xlabel(year_col, fontsize=12) ax.set_ylabel(value_col, fontsize=12) ax.legend(title=pivot_columns) ax.grid(True, alpha=0.3)# Add some annotations - show max and min valuesfor sex in pivot_data.columns: max_year = pivot_data[sex].idxmax() max_val = pivot_data[sex].max() ax.annotate(f"max: {max_val:.1f}", xy=(max_year, max_val), xytext=(5, 5), textcoords='offset points', fontsize=9)# Adjust the layout fig.tight_layout()# Add data source note fig.text(0.1, 0.01, "Data Source: WHO Xmart API", fontsize=8, style='italic')# Add a watermark to the center of the plot ax.text(0.95, 0.02, 'ToKnow.ai', ha='right', va='bottom', fontsize=18, color='gray', alpha=0.5, transform=ax.transAxes, rotation=45)def url_encode(url):return urllib.parse.quote(url, safe=":/?&=$")
Life expectancy, Kenya
The average number of years that a newborn could expect to live. Kenya, by sex, 2000 - 2021.
@misc{kabui2025,
author = {{Kabui, Charles}},
title = {Life {Expectancy} by Sex Between 2000 and 2021 in {Kenya}
{(WHO)}},
date = {2025-03-10},
url = {https://toknow.ai/posts/kenya-life-expectancy-between-2000-and-2021/index.html},
langid = {en-GB}
}