NITDA/NCAIR Logo

Unified Learning Archive

Python Expense Dashboard Tutorial

"A legacy that will echo till eternity"

Built by Group 5 • Powered by Elona • Honoring NITDA/NCAIR 🇳🇬

Expense Dashboard Visualization

Transform your receipt data into insightful visualizations with Python and Matplotlib

Complete Dashboard Tutorial

What You'll Build

This tutorial will teach you how to create an automated expense dashboard that:

  • Reads data from the expenses.csv file generated by the Receipt Manager
  • Calculates total spending by category
  • Generates professional visualizations with Matplotlib
  • Follows NITDA/NCAIR coding standards for maintainability

Complete Dashboard Implementation

import csv
from collections import defaultdict
import matplotlib.pyplot as plt


class ExpenseDataLoader:
    """
    📊 This class loads and organizes data from the expenses.csv file.
    """

    def __init__(self, csv_file='expenses.csv'):
        self.csv_file = csv_file
        self.category_totals = defaultdict(float)

    def load_data(self):
        """
        Reads the CSV and calculates the total price for each category.
        """
        try:
            with open(self.csv_file, 'r') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    category = row['Category']
                    price = float(row['Price'])
                    self.category_totals[category] += price
        except FileNotFoundError:
            print(f"❌ File not found: {self.csv_file}")
        except Exception as e:
            print(f"⚠ Error reading file: {e}")

        return self.category_totals


class ExpenseDashboard:
    """
    📈 This class handles chart creation and display.
    """

    def __init__(self, category_totals):
        self.categories = list(category_totals.keys())
        self.totals = list(category_totals.values())

    def show_bar_chart(self):
        """
        Creates and shows a bar chart of expenses per category.
        """
        plt.figure(figsize=(10, 6))
        bars = plt.bar(self.categories, self.totals, color='skyblue')
        plt.title('Total Expenses by Category')
        plt.xlabel('Category')
        plt.ylabel('Total (₦)')
        plt.xticks(rotation=30)
        plt.grid(axis='y')

        # Add labels on top of each bar
        for bar in bars:
            yval = bar.get_height()
            plt.text(bar.get_x() + bar.get_width()/2, yval + 5, f"₦{int(yval)}", 
                    ha='center', fontsize=9)

        plt.tight_layout()
        plt.show()


def main():
    print("📊 DASHBOARD VIEWER")
    print("🔁 Designed by Nuhu @ NITDA/NCAIR\n")

    # Step 1: Load data
    data_loader = ExpenseDataLoader()
    totals = data_loader.load_data()

    if totals:
        # Step 2: Create chart
        dashboard = ExpenseDashboard(totals)
        dashboard.show_bar_chart()
    else:
        print("⚠ No data to display.")


if __name__ == "__main__":
    main()

How to Use This Dashboard

  1. First run receipt_manager.py to process your receipts
  2. Save this code as dashboard.py in the same folder
  3. Run python dashboard.py
  4. View your expense visualization popup

Component Breakdown

ExpenseDataLoader Class

Responsible for loading and preparing the expense data from CSV.

__init__ method

Sets up the CSV file path and prepares a dictionary to store category totals.

load_data method

Reads the CSV file line by line, sums up prices by category, and handles potential file errors gracefully.

ExpenseDashboard Class

Handles the visualization of expense data.

__init__ method

Prepares the category names and totals for visualization.

show_bar_chart method

Creates a professional bar chart with labeled bars, proper formatting, and Naira currency symbols.

Step-by-Step Execution Flow

1

Program Starts

The main() function runs when you execute the script.

2

Data Loading

An ExpenseDataLoader instance reads and processes the CSV file.

3

Data Preparation

Category totals are calculated and returned as a dictionary.

4

Visualization

The ExpenseDashboard creates and displays the bar chart.

5

Result Display

A window pops up showing your categorized expenses in a professional chart.

NITDA/NCAIR Standards Implemented

Professional Visualization

  • Clean, labeled bar chart with Naira amounts
  • Proper axis labels and title
  • Responsive design that works for any category count

Robust Error Handling

  • Graceful handling of missing files
  • Clear error messages for troubleshooting
  • Data validation before processing

Modular Design

  • Separate classes for data loading and visualization
  • Clear separation of concerns
  • Easy to extend with new features

User Experience

  • Clear console output at each step
  • Professional chart formatting
  • Intuitive workflow from data to visualization

Expected Output

Sample Expense Visualization

When you run the dashboard with sample receipt data, you'll see a professional chart like this:

Sample bar chart

Example of a professional bar chart generated by Matplotlib

Chart Features:

  • Clear category labels on x-axis
  • Naira amounts displayed on each bar
  • Proper title and axis labels
  • Clean grid lines for easy reading
  • Responsive design that works with any data

Simple Explanations for Everyone

Two-line explanations so any Group 5 member can understand and explain confidently

📊 ExpenseDataLoader

Reads and organizes your expense data from the CSV file.
It adds up all purchases in each category (Food, Personal Care, etc.) automatically.

__init__ method

Prepares the system to read your expense file.
Creates an empty "calculator" to track category totals.

load_data method

Goes through each purchase in the file line by line.
Adds each item's price to its category's running total.

📈 ExpenseDashboard

Turns numbers into visual charts you can understand at a glance.
Creates professional bar charts showing where your money went.

__init__ method

Organizes the data for charting.
Separates category names from their total amounts.

show_bar_chart method

Draws the actual bar chart with colored bars.
Adds labels, titles, and Naira amounts for clarity.

🖥️ Main Function

The "conductor" that runs everything in the right order.
First loads data, then creates the chart, just like following a recipe.

if __name__ block

This is where the program starts when you run it.
Like pressing the "ON" button to begin the whole process.

💡 How It All Works Together

Data Flow

  1. CSV file → DataLoader → Category Totals
  2. Totals → Dashboard → Visual Chart

Key Benefits

  • See spending patterns instantly
  • No manual calculations needed
  • Professional results automatically

Now you can explain this dashboard like a pro! 🎤

Line-by-Line Code Breakdown

Complete explanation in plain English for absolute beginners

import csv
from collections import defaultdict
import matplotlib.pyplot as plt

What These Imports Do:

  • csv - Lets Python read spreadsheet files (like your expenses.csv)
  • defaultdict - Creates automatic category totals without errors
  • matplotlib - The tool that draws the colorful bar charts

Think of these like kitchen tools - each has a special job for our recipe.

1 The DataLoader Class

def __init__(self, csv_file='expenses.csv'):
    self.csv_file = csv_file
    self.category_totals = defaultdict(float)

In Simple Terms: This sets up our "data calculator":

  1. Remembers your expenses file name
  2. Creates an empty tally sheet for categories

Like preparing a blank notebook before taking inventory.

def load_data(self):
    try:
        with open(self.csv_file, 'r') as file:
            reader = csv.DictReader(file)
            for row in reader:
                category = row['Category']
                price = float(row['Price'])
                self.category_totals[category] += price

Step-by-Step:

  1. Opens your expenses file carefully (try)
  2. Reads each purchase line by line
  3. Adds each item's price to its category's total

Real-world example: Like sorting receipts into piles (Food, Toiletries) and adding each pile's total.

2 The Dashboard Class

def __init__(self, category_totals):
    self.categories = list(category_totals.keys())
    self.totals = list(category_totals.values())

What Happens:

  1. Takes the calculated category totals
  2. Prepares two separate lists:
    • Category names (Food, Toiletries)
    • Their total amounts (₦3500, ₦2800)
def show_bar_chart(self):
    plt.figure(figsize=(10, 6))
    bars = plt.bar(self.categories, self.totals, color='skyblue')
    plt.title('Total Expenses by Category')
    plt.xlabel('Category')
    plt.ylabel('Total (₦)')
    plt.xticks(rotation=30)
    plt.grid(axis='y')
    
    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width()/2, height + 5, 
                f"₦{int(height)}", ha='center')

Chart Creation Steps:

  1. Sets up the canvas size (10x6 inches)
  2. Draws blue bars for each category
  3. Adds titles and rotates labels for readability
  4. Puts exact Naira amounts on each bar
  5. Adds subtle grid lines for easier comparison

Like an artist carefully labeling a graph for a school project.

🚀 The Main Function

def main():
    print("📊 DASHBOARD VIEWER")
    print("🔁 Designed by Nuhu @ NITDA/NCAIR\n")
    
    data_loader = ExpenseDataLoader()
    totals = data_loader.load_data()
    
    if totals:
        dashboard = ExpenseDashboard(totals)
        dashboard.show_bar_chart()
    else:
        print("⚠ No data to display.")

How Everything Connects:

  1. Shows a friendly welcome message
  2. Creates the data loader to read your file
  3. If data exists, makes and shows the chart
  4. If no data, gives a helpful warning

Pro Tip: This is like the "start button" that runs the whole process in the right order.

Dashboard Q&A Challenge

Test your knowledge with these 30 essential visualization questions

1. What is the purpose of defaultdict in ExpenseDataLoader?

+

2. Why does show_bar_chart() rotate x-axis labels by 30 degrees?

+

3. What happens if expenses.csv is empty when running the dashboard?

+

4. What does csv.DictReader do in the ExpenseDataLoader?

+

5. Why is there a try/except block in load_data()?

+

6. What color are the bars in the default chart?

+

7. What does plt.grid(axis='y') add to the chart?

+

8. What does bar.get_height() return?

+

9. Why convert row['Price'] to float?

+

10. What is the purpose of plt.tight_layout()?

+

11. What is the first thing the main() function does?

+

12. How are the category totals stored in ExpenseDashboard?

+

13. What appears on the y-axis of the chart?

+

14. What size is the chart set to create?

+

15. What does ha='center' do in plt.text()?

+

16. What is the best use of this dashboard?

+

17. What does plt.xlabel() configure?

+

18. Why use defaultdict(float) instead of a regular dictionary?

+

19. Which of these is NOT shown in the chart?

+

20. How are categories sorted in the chart?

+

21. What handles the case when there's no data to display?

+

22. Where does the ₦ symbol come from in the chart?

+

23. What does plt.ylabel() configure?

+

24. Why convert height to int in the bar labels?

+

25. What is the default title of the chart?

+

26. What does the += operator do in category_totals[category] += price?

+

27. Where are the value labels placed on the bars?

+

28. What Python feature opens and automatically closes the CSV file?

+

29. What is the 'reader' variable in load_data()?

+

30. What does plt.tight_layout() do in the chart?

+