Task 4a · Matplotlib
up to +100 XP
Stop 4a.4 · Task 4a · 6 min

Matplotlib

Create effective visualizations with Pandas and Matplotlib

Learning Objectives:
  • Learn to create bar charts, line graphs, and pie charts
  • Master useful plotting techniques for Task 4a
  • Add values on bars, bigger points, grids, and labels
  • Customize plots for clear data presentation

Getting Started

Matplotlib works with Pandas to visualize your data. Always import both:

import pandas as pd
import matplotlib.pyplot as plt

# Read your data
df = pd.read_csv("Task4a_data.csv")

Bar Charts

Bar charts compare categories. Perfect for showing sales by model or salesperson.

Basic Bar Chart

# Group data and create bar chart
model_totals = df.groupby('Car Model')['Value'].sum()

plt.figure(figsize=(10, 6))
plt.bar(model_totals.index, model_totals.values)
plt.title('Total Sales by Car Model')
plt.xlabel('Car Model')
plt.ylabel('Total Sales (£)')
plt.show()

Image placeholder: [Basic bar chart showing 5 car models with different height bars]

Add Values on Top of Bars

Show exact values on each bar for clarity:

plt.figure(figsize=(10, 6))
bars = plt.bar(model_totals.index, model_totals.values)

# Add value labels on top of each bar
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'£{height:,.0f}',
             ha='center', va='bottom', fontsize=10)

plt.title('Total Sales by Car Model')
plt.xlabel('Car Model')
plt.ylabel('Total Sales (£)')
plt.show()

What this does: Loops through each bar and adds text showing the value above it

Image placeholder: [Bar chart with "£45,000", "£38,500" etc. displayed above each bar]

Rotate X-axis Labels

Prevent overlapping labels with long names:

plt.figure(figsize=(10, 6))
plt.bar(model_totals.index, model_totals.values)
plt.title('Total Sales by Car Model')
plt.xlabel('Car Model')
plt.ylabel('Total Sales (£)')
plt.xticks(rotation=45, ha='right')  # Rotate labels 45 degrees
plt.tight_layout()  # Prevent labels being cut off
plt.show()

What this does: rotation=45 tilts labels, ha='right' aligns them right, tight_layout() fits everything in

Image placeholder: [Bar chart with diagonal x-axis labels]

Add Grid Lines

Grids help read values more accurately:

plt.figure(figsize=(10, 6))
plt.bar(model_totals.index, model_totals.values)
plt.title('Total Sales by Car Model')
plt.xlabel('Car Model')
plt.ylabel('Total Sales (£)')
plt.grid(True, axis='y', alpha=0.3)  # Horizontal grid lines only
plt.show()

What this does: grid(True) adds grid, axis='y' only horizontal lines, alpha=0.3 makes them faint

Image placeholder: [Bar chart with faint horizontal grid lines in background]

Change Bar Colors

plt.figure(figsize=(10, 6))
plt.bar(model_totals.index, model_totals.values, color='#FFB15C')  # Orange
plt.title('Total Sales by Car Model')
plt.xlabel('Car Model')
plt.ylabel('Total Sales (£)')
plt.show()

What this does: color='#FFB15C' sets all bars to orange (use hex codes or names like 'blue', 'red')

Line Graphs

Line graphs show trends over time. Perfect for monthly sales or patterns.

Basic Line Graph

# Convert date and group by month
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
monthly_sales = df.groupby(df['Date'].dt.to_period('M'))['Value'].sum()

plt.figure(figsize=(10, 6))
plt.plot(monthly_sales.index.astype(str), monthly_sales.values)
plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Total Sales (£)')
plt.show()

Image placeholder: [Line graph showing upward trend across months]

Make Points Bigger and Stand Out

plt.figure(figsize=(10, 6))
plt.plot(monthly_sales.index.astype(str), monthly_sales.values,
         marker='o',           # Circle markers at each point
         markersize=10,        # Make markers bigger
         linewidth=2,          # Thicker line
         color='#C2410C')      # Blue line

plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Total Sales (£)')
plt.grid(True, alpha=0.3)
plt.show()

What this does: marker='o' adds circles, markersize=10 makes them big, linewidth=2 thickens the line

Image placeholder: [Line graph with large visible dots at each data point]

Multiple Lines for Comparison

# Compare New vs Used sales over time
new_sales = df[df['New/Used'] == 'New'].groupby(df['Date'].dt.to_period('M'))['Value'].sum()
used_sales = df[df['New/Used'] == 'Used'].groupby(df['Date'].dt.to_period('M'))['Value'].sum()

plt.figure(figsize=(10, 6))
plt.plot(new_sales.index.astype(str), new_sales.values, 
         marker='o', markersize=8, linewidth=2, label='New Cars')
plt.plot(used_sales.index.astype(str), used_sales.values, 
         marker='s', markersize=8, linewidth=2, label='Used Cars')

plt.title('New vs Used Car Sales Over Time')
plt.xlabel('Month')
plt.ylabel('Total Sales (£)')
plt.legend()  # Show which line is which
plt.grid(True, alpha=0.3)
plt.show()

What this does: label='New Cars' names the line, plt.legend() displays the legend box

Image placeholder: [Two lines (different colors) with legend showing "New Cars" and "Used Cars"]

Pie Charts

Pie charts show proportions. Good for market share or category breakdown.

Basic Pie Chart

# Sales by salesperson
salesperson_totals = df.groupby('Salesperson')['Value'].sum()

plt.figure(figsize=(8, 8))
plt.pie(salesperson_totals.values, labels=salesperson_totals.index)
plt.title('Sales by Salesperson')
plt.show()

Image placeholder: [Pie chart divided into colored segments with names]

Add Percentages

plt.figure(figsize=(8, 8))
plt.pie(salesperson_totals.values, 
        labels=salesperson_totals.index,
        autopct='%1.1f%%')  # Show percentages with 1 decimal place

plt.title('Sales by Salesperson')
plt.show()

What this does: autopct='%1.1f%%' displays percentage on each slice (e.g., "25.3%")

Image placeholder: [Pie chart with "25.3%", "18.7%" etc. on each slice]

Explode a Slice

Pull out one slice to highlight it:

plt.figure(figsize=(8, 8))
explode = (0.1, 0, 0, 0)  # Pull out first slice by 0.1

plt.pie(salesperson_totals.values, 
        labels=salesperson_totals.index,
        autopct='%1.1f%%',
        explode=explode)  # Apply the explode

plt.title('Sales by Salesperson')
plt.show()

What this does: explode=(0.1, 0, 0, 0) pulls first slice out, others stay in place

Image placeholder: [Pie chart with one slice slightly separated from the rest]

Useful Customizations

Figure Size

plt.figure(figsize=(12, 6))  # Width=12 inches, Height=6 inches

What this does: Makes the plot bigger or smaller. Larger = more detail, easier to read

Title and Labels

plt.title('Total Sales by Car Model', fontsize=16, fontweight='bold')
plt.xlabel('Car Model', fontsize=12)
plt.ylabel('Total Sales (£)', fontsize=12)

What this does: fontsize changes text size, fontweight='bold' makes title bold

Save the Plot

plt.savefig('sales_chart.png', dpi=300, bbox_inches='tight')

What this does: Saves plot as image file. dpi=300 = high quality, bbox_inches='tight' = no white space

Show the Plot

plt.show()

What this does: Displays the plot. Always call this at the end!

Complete Example for Task 4a

import pandas as pd
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv("Task4a_data.csv")

# Group by car model
model_totals = df.groupby('Car Model')['Value'].sum()

# Create bar chart
plt.figure(figsize=(12, 6))
bars = plt.bar(model_totals.index, model_totals.values, color='#C2410C')

# Add values on bars
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'£{height:,.0f}',
             ha='center', va='bottom', fontsize=10)

# Customize
plt.title('Total Sales by Car Model', fontsize=16, fontweight='bold')
plt.xlabel('Car Model', fontsize=12)
plt.ylabel('Total Sales (£)', fontsize=12)
plt.xticks(rotation=45, ha='right')
plt.grid(True, axis='y', alpha=0.3)
plt.tight_layout()

# Display
plt.show()

Quick Reference

Bar Chart Essentials

Line Graph Essentials

Pie Chart Essentials

General Tips

Common Task 4a Scenarios

Scenario 1: Compare New vs Used Sales

# Bar chart comparing categories
new_used = df.groupby('New/Used')['Value'].sum()

plt.figure(figsize=(8, 6))
bars = plt.bar(new_used.index, new_used.values, color=['#C2410C', '#FFB15C'])

for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'£{height:,.0f}', ha='center', va='bottom')

plt.title('New vs Used Car Sales')
plt.ylabel('Total Sales (£)')
plt.grid(True, axis='y', alpha=0.3)
plt.show()

Scenario 2: Salesperson Performance

# Horizontal bar chart for easy name reading
salesperson_totals = df.groupby('Salesperson')['Value'].sum().sort_values()

plt.figure(figsize=(10, 6))
plt.barh(salesperson_totals.index, salesperson_totals.values, color='#C2410C')
plt.title('Sales by Salesperson')
plt.xlabel('Total Sales (£)')
plt.grid(True, axis='x', alpha=0.3)
plt.tight_layout()
plt.show()

What this does: plt.barh() creates horizontal bars, easier to read long names

Scenario 3: Monthly Trend

# Line graph showing trend over time
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
monthly = df.groupby(df['Date'].dt.to_period('M'))['Value'].sum()

plt.figure(figsize=(10, 6))
plt.plot(monthly.index.astype(str), monthly.values,
         marker='o', markersize=10, linewidth=2, color='#C2410C')

plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Total Sales (£)')
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Quick check · 10 questions

Check what stuck.

+10 XP each
Question 1

Question 1 of 10

What import statement is needed for matplotlib?

Question 2

Question 2 of 10

How do you create a bar chart?

Question 3

Question 3 of 10

How do you add markers to a line plot?

Question 4

Question 4 of 10

How do you make markers bigger on a line plot?

Question 5

Question 5 of 10

How do you add a grid to your plot?

Question 6

Question 6 of 10

How do you rotate x-axis labels 45 degrees?

Question 7

Question 7 of 10

How do you add a title to a plot?

Question 8

Question 8 of 10

What does plt.tight_layout() do?

Question 9

Question 9 of 10

How do you display the plot?

Question 10

Question 10 of 10

How do you set figure size to 10x6 inches?