Data Visualization with Matplotlib
A good chart shows a pattern in seconds that would take minutes to find in a table of numbers.
Getting Started with Matplotlib
matplotlib is the most used charting library in Python. Its pyplot module is imported as plt:
Example
import matplotlib.pyplot as pltInstall it with pip install matplotlib if you have not already. In Jupyter, charts appear under the cell. In a normal Python script, call plt.show() to open a window with the chart.
Your First Line Chart
A line chart shows how something changes over time. Monthly sales of a mobile shop:
Example
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 135, 128, 160, 190, 175]
plt.plot(months, sales, marker="o")
plt.title("Monthly Sales (thousand Rs)")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(True)
plt.show()The chart shows a line rising from 120 in January to a peak of 190 in May, with a dot at each month.
Always add a title and axis labels. A chart without labels makes the reader guess what the numbers mean.
Choosing the Right Chart
| Chart | Function | Use it to show |
|---|---|---|
| Line | plt.plot() | Change over time |
| Bar | plt.bar() | Comparing categories |
| Horizontal bar | plt.barh() | Comparing categories with long names |
| Histogram | plt.hist() | How values are spread (distribution) |
| Scatter | plt.scatter() | The relationship between two numbers |
| Pie | plt.pie() | Parts of a whole (use only with a few parts) |
Bar Chart
Compare total sales of the three bakery branches from the analysis chapter:
Example
branches = ["Orangi", "Saddar", "Gulshan"]
totals = [7550, 6500, 4200]
plt.bar(branches, totals, color="#0891b2")
plt.title("Sales by Branch (Rs)")
plt.ylabel("Total sales")
plt.show()Three bars appear, the tallest for Orangi. Sorting categories from largest to smallest, as here, makes bar charts easier to read.
Plotting Straight from pandas
DataFrames and Series have a .plot() method that uses matplotlib for you:
Example
import pandas as pd
df = pd.read_csv("sales.csv")
df["total"] = df["quantity"] * df["price"]
by_item = df.groupby("item")["total"].sum().sort_values()
by_item.plot(kind="barh", title="Sales by Item (Rs)")
plt.xlabel("Total sales")
plt.show()
print(by_item)item Biscuits 3250 Bread 4200 Cake 10800 Name: total, dtype: int64
The kind option can be "line", "bar", "barh", "hist", "scatter", "pie" or "box".
Histogram
A histogram groups numbers into ranges called bins and shows how many values fall in each one:
Example
marks = [45, 52, 58, 61, 63, 66, 68, 70, 71, 73, 75, 78, 81, 85, 92]
plt.hist(marks, bins=5, edgecolor="black")
plt.title("Distribution of Marks")
plt.xlabel("Marks")
plt.ylabel("Number of students")
plt.show()Most bars are in the middle (60 to 80), with few students at the low and high ends.
Scatter Plot
A scatter plot shows whether two values move together. Do students who study more hours get higher marks?
Example
hours = [1, 2, 3, 4, 5, 6, 7, 8]
scores = [35, 42, 50, 55, 63, 68, 77, 82]
plt.scatter(hours, scores)
plt.title("Study Hours vs Marks")
plt.xlabel("Hours studied per week")
plt.ylabel("Marks")
plt.show()The dots form a line going up to the right: more study hours go with higher marks. You will measure this with a number in the next chapter.
Several Charts Together
plt.subplots() creates a figure with several charts side by side:
Example
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
left.bar(branches, totals)
left.set_title("By Branch")
right.plot(months, sales, marker="o")
right.set_title("By Month")
plt.tight_layout()
plt.show()Saving a Chart
Save the chart as an image to put in a report or presentation. Call savefig before show:
Example
plt.bar(branches, totals)
plt.title("Sales by Branch (Rs)")
plt.savefig("branch_sales.png", dpi=150, bbox_inches="tight")Exercise
Exercise
Which chart is best for showing how a shop's sales changed month by month over a year?
