Tutorial 4: Data Visualization with Matplotlib

Introduction

Data visualization means representing data using charts and graphs. Instead of only looking at raw numbers, visualization helps us quickly spot trends, comparisons, distributions, relationships, patterns, and outliers.

Data → Matplotlib → Charts & Graphs → Visual Insights

By the end of this chapter, you’ll be able to create: line charts, bar charts, histograms, scatter plots, and customized charts.


1. Import Matplotlib

import matplotlib.pyplot as plt

pyplot is commonly given the alias plt.


2. Create Sample Data

months = ["January", "February", "March", "April", "May", "June"]
sales = [10000, 15000, 12000, 18000, 22000, 20000]

3. Line Chart

A line chart is best for showing trends over time.

plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

Add markers to highlight each data point:

plt.plot(months, sales, marker="o")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

When to use a line chart? Whenever you’re plotting something against time — time vs. sales, time vs. temperature, time vs. revenue, time vs. website visitors.


4. Bar Chart

A bar chart is useful for comparing categories.

departments = ["IT", "HR", "Finance", "Sales"]
employees = [25, 10, 18, 15]

plt.bar(departments, employees)
plt.title("Employees by Department")
plt.xlabel("Department")
plt.ylabel("Number of Employees")
plt.show()

When to use a bar chart? Department vs. employees, product vs. sales, city vs. population, category vs. revenue — anywhere you’re comparing discrete groups against each other.


5. Horizontal Bar Chart

Sometimes horizontal bars are easier to read, especially when category names are long:

plt.barh(departments, employees)
plt.title("Employees by Department")
plt.xlabel("Number of Employees")
plt.ylabel("Department")
plt.show()

6. Histogram

A histogram shows the distribution of numerical data — how values are spread across ranges (called “bins”).

salaries = [
    45000, 50000, 52000, 55000,
    60000, 62000, 65000, 68000,
    70000, 75000, 80000, 85000,
    90000, 95000, 100000
]

plt.hist(salaries)
plt.title("Salary Distribution")
plt.xlabel("Salary")
plt.ylabel("Number of Employees")
plt.show()

A histogram helps answer: how are the salary values distributed? For example: most employees earn between ₹50,000 and ₹80,000.


7. Scatter Plot

A scatter plot shows the relationship between two numerical variables — each point represents one data pair.

experience = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
salary = [
    30000, 35000, 40000, 45000, 50000,
    58000, 65000, 72000, 80000, 90000
]

plt.scatter(experience, salary)
plt.title("Experience vs Salary")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()

Possible insight: as experience increases, salary generally increases too — suggesting a positive relationship between the two variables.


8. Create a Figure and Axes (the “professional” approach)

fig, ax = plt.subplots()

ax.plot(months, sales)
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
plt.show()

This object-oriented style (fig, ax = plt.subplots()) gives you more explicit control — especially useful once you start creating multiple charts side-by-side (subplots), which the simpler plt.plot() style doesn’t handle as cleanly.


9. Add a Grid

plt.plot(months, sales, marker="o")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.show()

A grid can make it easier to read exact values off the chart.


10. Add Data Labels

plt.bar(departments, employees)
plt.title("Employees by Department")

for i, value in enumerate(employees):
    plt.text(i, value, str(value), ha="center")

plt.show()

enumerate() gives us both the position (i) and value of each bar, so plt.text() can place the actual number just above it.


11. Create a Chart Directly from a Pandas DataFrame

import pandas as pd

data = {
    "Month": ["January", "February", "March", "April", "May", "June"],
    "Sales": [10000, 15000, 12000, 18000, 22000, 20000]
}

df = pd.DataFrame(data)
df

Now create a chart directly from the DataFrame:

df.plot(x="Month", y="Sales", kind="line", marker="o")
plt.title("Monthly Sales")
plt.show()

Pandas uses Matplotlib internally for many of its visualizations — this is a shortcut that saves you from writing out the full plt.plot() call.


12. Choosing the Right Chart

ChartBest Used For
Line ChartTrends over time
Bar ChartComparing categories
HistogramDistribution of values
Scatter PlotRelationship between variables

Quick decision guide: Want to show a trend? → Line chart. Want to compare categories? → Bar chart. Want to understand distribution? → Histogram. Want to study relationships? → Scatter plot.


Complete Example

import matplotlib.pyplot as plt

months = ["January", "February", "March", "April", "May", "June"]
sales = [10000, 15000, 12000, 18000, 22000, 20000]

plt.plot(months, sales, marker="o")
plt.title("Monthly Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid()
plt.show()

Analysis: sales increased from January to February, dipped in March, then rose strongly from March through May — the highest point in the dataset — before decreasing slightly in June. This is the entire purpose of visualization: converting numbers into visual insight.


Practice Exercise

Using the employee dataset from Chapter 2, create: a bar chart of employees by department, a histogram of salary distribution, a scatter plot of experience vs. salary, and a line chart of monthly sales.

Scroll to Top