How to create your first line chart with World Bank Kenya GDP data

Learn how to pull Kenya GDP data directly from the World Bank API and create your first line chart in Python using pandas and matplotlib—clean, fast, and reproducible.

1. Install Required Libraries

!pip install pandas matplotlib wbdata



2. Import Dependencies

import pandas as pd
import matplotlib.pyplot as plt
import wbdata
import datetime


3. Define the Data You Need

World Bank uses indicators. For GDP (current US$), the indicator is:

NY.GDP.MKTP.CD

Set the country to Kenya (KEN) and define a time range:

indicator = {'NY.GDP.MKTP.CD': 'gdp'}

data_date = (datetime.datetime(2000, 1, 1), datetime.datetime(2023, 1, 1))






4. Fetch Data from World Bank

df = wbdata.get_dataframe(indicator, country='KEN', data_date=data_date)



5. Clean and Prepare Data

df = df.reset_index()
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date')
print (df)





Explanation
  • df = df.reset_index() → Converts the index into a normal column and resets row numbering

  • df['date'] = pd.to_datetime(df['date']) → Converts the date column to proper datetime format

  • df = df.sort_values('date') → Orders the DataFrame chronologically by date

  • print(df) displays the data as it is.


6. Create the Line Chart

plt.figure()
plt.plot(df['date'], df['gdp'])

plt.title('Kenya GDP Over Time')
plt.xlabel('Year')
plt.ylabel('GDP (Current US$)')

plt.show()




Explanation:
  • plt.figure() → Initializes a new plotting canvas (separates this chart from others)

  • plt.plot(df['date'], df['gdp']) → Draws a line chart with:

    • x-axis = dates (df['date'])

    • y-axis = GDP values (df['gdp'])

  • plt.title('Kenya GDP Over Time') → Sets the chart title

  • plt.xlabel('Year') → Labels the x-axis

  • plt.ylabel('GDP (Current US$)') → Labels the y-axis

  • plt.show() → Renders and displays the chart


You’re creating and displaying a time-series line chart of Kenya’s GDP.


7. What You Just Did (Key Concepts Only)

  • API Data Retrieval → Pulled structured economic data directly from the World Bank

  • Time Series Preparation → Converted and sorted dates for correct plotting

  • Line Chart → Visualized GDP trends over time


8. Expected Output

A simple line chart showing Kenya’s GDP growth from 2000 to 2024. The x-axis represents years, and the y-axis shows GDP in current US dollars.


This workflow is production-ready: reproducible, API-driven, and suitable for dashboards or reporting pipelines.



Advance Your Career With 16 Python Projects in Data & ML — All for $288.

Comments

Popular posts from this blog

How to Filter Rows Using Boolean Indexing in Pandas (Afrobarometer Kenya Dataset)

How to Decide Whether to Drop or Fill Missing Value