Skip to main content

Chapter 7: Matplotlib Visualization

MODULE 2 | WEEK 7​

Chapter 7: Matplotlib Visualization​

Long tables of numbers make no sense when you look at them, but a chart tells the story at a glance. Data Visualization means giving data the form of a picture so that patterns, trends and strange things become visible immediately. Matplotlib is Python's most fundamental plotting library, and Seaborn and Pandas charts are also built on it.

7.1 Why Data Visualization?​

7.2 The first chart: plt.plot()​

import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5, 6, 7]
temp = [31, 33, 32, 35, 36, 34, 33]
plt.plot(days, temp)
plt.show()
OUTPUT (chart)​
7.2 The first chart: plt.plot(): 36 35 34 33 32 31
7.2 The first chart: plt.plot(): 36 35 34 33 32 31

The chart was made in just a few lines. plt.plot(x, y) draws the line, and plt.show() displays it on the screen. But this chart has no title and no labels. A chart like this tells you nothing. Let us fix it.

plt.figure(figsize=(7, 3.8))
plt.plot(days, temp, color="crimson", marker="o", linestyle="--", linewidth=2)
plt.title("Weekly temperature (Karachi)")
plt.xlabel("Day")
plt.ylabel("Temperature (C)")
plt.grid(True, alpha=0.3)
plt.show()
OUTPUT (chart)​
7.2 The first chart: plt.plot(): Weeklytemperature(Karachi) 36 35 Temperature (C) 34 33 32 31 Day
7.2 The first chart: plt.plot(): Weeklytemperature(Karachi) 36 35 Temperature (C) 34 33 32 31 Day

7.3 Two ways of using Matplotlib​

There are two styles of making a chart in Matplotlib. Both are correct, but as charts get bigger the second way is better.

1) pyplot style2) Object-Oriented (fig, ax) style
Howplt.plot(), plt.title()...fig, ax = plt.subplots(); ax.plot(), ax.set_title()
1) pyplot style2) Object-Oriented (fig, ax) style
Best whenSmall and quick chartsMany charts (subplots), big figures, professional work
In shortFor small jobsFor more control
OUTPUT (chart)​
ANALOGY: Same chart,Object-Oriented style 36 35 Temperature (C) 34 33 32 31 Day
ANALOGY: Same chart,Object-Oriented style 36 35 Temperature (C) 34 33 32 31 Day

7.4 Types of charts (which chart when)​

ChartWhen to useExample question
LineChange over time (trend)How were sales month by month?
BarComparison of different categoriesHow many students are in each city?
HistogramDistributionof one numeric variableBetween which numbers do most students' marks
lie?
ScatterRelationship betweentwo numericvariablesDo marks go up as study hours go up?
PieShare of a whole (few categories, at most 5)How much of the spending went on what?
Box plotDistribution, median and outliersWhich class has more variation in marks?

Bar chart​

cities = ["Karachi", "Lahore", "Islamabad", "Quetta"]
students = [120, 95, 60, 35]
plt.figure(figsize=(7, 3.8))
plt.bar(cities, students, color=["#A4457A", "#6B5B95", "#E8A5C0", "#2F7D4F"])
plt.title("Students by city")
plt.ylabel("Number of students")
plt.show()
OUTPUT (chart)​
Bar chart: Studentsby city 120 100 Number of students 80 60 40 Karachi Lahore Islamabad Quetta
Bar chart: Studentsby city 120 100 Number of students 80 60 40 Karachi Lahore Islamabad Quetta

If the names are long, plt.barh() (horizontal bar) works better.

plt.figure(figsize=(7, 3.2))
plt.barh(cities, students, color="#6B5B95")
plt.title("Horizontal bar chart")
plt.xlabel("Number of students")
plt.show()
OUTPUT (chart)​
Bar chart: Horizontal bar chart Quetta Islamabad Lahore Karachi 20 80 40 60 100 120 Number of students
Bar chart: Horizontal bar chart Quetta Islamabad Lahore Karachi 20 80 40 60 100 120 Number of students

Histogram (looking at a distribution)​

A histogram divides the data into bins (boxes) and shows how many values fell into each bin.

import numpy as np
np.random.seed(1)
marks = np.random.normal(loc=65, scale=12, size=200).round() # marks of 200 students
plt.figure(figsize=(7, 3.8))
plt.hist(marks, bins=10, color="#A4457A", edgecolor="white")
plt.title("Distribution of marks of 200 students")
plt.xlabel("Marks")
plt.ylabel("Number of students")
plt.axvline(marks.mean(), color="black", linestyle="--", label="Average")
plt.legend()
plt.show()
OUTPUT (chart)​
Histogram (looking at a distribution): Distributionofmarksof200students 50 Average 40 Number of students 30 20 10 40 50 60 70 80 90 Marks
Histogram (looking at a distribution): Distributionofmarksof200students 50 Average 40 Number of students 30 20 10 40 50 60 70 80 90 Marks

Scatter plot (relationship between two things)​

np.random.seed(2)
hours = np.random.uniform(1, 10, 60) # study hours
score = 35 + 6 * hours + np.random.normal(0, 6, 60) # marks (with a little noise)
plt.figure(figsize=(7, 3.8))
plt.scatter(hours, score, color="#6B5B95", alpha=0.7)
plt.title("Study hours and marks")
plt.xlabel("Hours")
plt.ylabel("Marks")
plt.show()
OUTPUT (chart)​
Scatter plot (relationship between two things): Studyhoursandmarks 90 80 Marks 70 60 50 40 10 Hours
Scatter plot (relationship between two things): Studyhoursandmarks 90 80 Marks 70 60 50 40 10 Hours

The dots appear to go from the bottom to the top: the more hours, the more marks . This is called positive correlation (in detail in Module 3).

Pie chart​

labels = ["Food", "Rent", "Transport", "Savings"]
amounts = [30, 40, 10, 20]
plt.figure(figsize=(5, 4))
plt.pie(amounts, labels=labels, autopct="%1.0f%%", startangle=90,
colors=["#E8A5C0", "#6B5B95", "#B7791F", "#2F7D4F"])
plt.title("Monthly expenses")
plt.show()
OUTPUT (chart)​
Pie chart: Monthlyexpenses Savings Food 20% 30% 10% Transport 40% Rent
Pie chart: Monthlyexpenses Savings Food 20% 30% 10% Transport 40% Rent

Box plot​

np.random.seed(3)
class_a = np.random.normal(70, 8, 50)
class_b = np.random.normal(60, 15, 50)
plt.figure(figsize=(6, 3.8))
plt.boxplot([class_a, class_b], tick_labels=["Class A", "Class B"])
plt.title("Comparison of the marks of two classes")
plt.ylabel("Marks")
plt.show()
OUTPUT (chart)​
Box plot: Comparisonofthemarksoftwoclasses 90 80 70 Marks 60 50 40 20 Class A Class B
Box plot: Comparisonofthemarksoftwoclasses 90 80 70 Marks 60 50 40 20 Class A Class B

7.5 Plot Customization​

ItemHowExample
Title / Labelstitle(), xlabel(), ylabel()plt.title("Sales")
Colourcolor="red", "#A4457A"
Line stylelinestyle= ('-', '--', ':', '-.')linestyle="--"
Line thicknesslinewidth=linewidth=2
Markermarker= ('o', 's', '^', '*')marker="o"
Transparencyalpha= (0 to 1)alpha=0.5
Label and Legendlabel=, plt.legend()plt.plot(x, y, label="A")
Gridplt.grid()plt.grid(True, alpha=0.3)
Axis limitsxlim(), ylim()plt.ylim(0, 100)
Axis ticksxticks(rotation=)plt.xticks(rotation=45)
Chart sizefigure(figsize=(w, h))figsize=(8, 4)
Text / Annotationannotate(), text()plt.annotate(...)
Styleplt.style.use()plt.style.use("ggplot")
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
shop_a = [40, 45, 50, 62, 70, 78]
shop_b = [55, 52, 58, 60, 59, 65]
plt.figure(figsize=(7.5, 4))
plt.plot(months, shop_a, marker="o", linewidth=2, color="#A4457A", label="Shop A")
plt.plot(months, shop_b, marker="s", linewidth=2, linestyle="--", color="#6B5B95",
label="Shop B")
plt.title("Sales of two shops (thousand Rs.)", fontsize=13, fontweight="bold")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.ylim(0, 90)
plt.grid(True, alpha=0.3)
plt.legend()
plt.annotate("Shop A took the lead", xy=("Apr", 62), xytext=("Jan", 75),
arrowprops=dict(arrowstyle="->"))
plt.show()
OUTPUT (chart)​
7.5 Plot Customization: Sales of two shops (thousand Rs.) 90 80 ShopAtookthelead 70 60 Sales 40 10 Shop A Shop B Feb Jan Mar Apr May jun Month
7.5 Plot Customization: Sales of two shops (thousand Rs.) 90 80 ShopAtookthelead 70 60 Sales 40 10 Shop A Shop B Feb Jan Mar Apr May jun Month

7.6 Subplots (many charts in one figure)​

plt.subplots(rows, columns) creates several charts in one figure at once. This is the basic way to build a dashboard.

fig, axes = plt.subplots(2, 2, figsize=(9, 6))
axes[0, 0].plot(months, shop_a, color="#A4457A", marker="o")
axes[0, 0].set_title("Line: Shop A")
axes[0, 1].bar(cities, students, color="#6B5B95")
axes[0, 1].set_title("Bar: City")
axes[1, 0].hist(marks, bins=10, color="#2F7D4F", edgecolor="white")
axes[1, 0].set_title("Histogram: Marks")
axes[1, 1].scatter(hours, score, color="#B7791F", alpha=0.7)
axes[1, 1].set_title("Scatter: Hours vs Marks")
fig.suptitle("Four charts in one figure", fontsize=14, fontweight="bold")
plt.tight_layout()
plt.show()
OUTPUT (chart)​
7.6 Subplots (many charts in one figure): Four charts in one figure Line: Shop A Bar: City 120 70 100 80 60 60 50 40 40 Feb May Mar Apr Karachi Lahore Islamabad Jan jun Quetta Histogram:Marks Scatter: Hours vs Marks 50...
7.6 Subplots (many charts in one figure): Four charts in one figure Line: Shop A Bar: City 120 70 100 80 60 60 50 40 40 Feb May Mar Apr Karachi Lahore Islamabad Jan jun Quetta Histogram:Marks Scatter: Hours vs Marks 50...

Saving a chart​

fig.savefig("dashboard.png", dpi=150, bbox_inches="tight") # PNG file created
import os
print(os.path.exists("dashboard.png"))
OUTPUT​
True

In Colab you can download this file using the folder icon on the left side. The higher the dpi , the sharper the picture.

7.7 Real-world Data Visualization​

Now let us put everything together in a real example. We have data for 12 months of sales of a shop. We will build the data with Pandas and answer several questions with charts.

import pandas as pd
import numpy as np
np.random.seed(7)
months = pd.date_range("2025-01-01", periods=12, freq="MS").strftime("%b")
df = pd.DataFrame({
"month": months,
"sales": (np.linspace(200, 330, 12) + np.random.normal(0, 15, 12)).round(),
"ads_budget": np.linspace(20, 60, 12).round() + np.random.randint(-4, 5, 12),
})
df["profit"] = (df["sales"] * 0.25 - df["ads_budget"]).round(1)
print(df.head())
OUTPUT​
month sales ads_budget profit
0 Jan 225.0 22.0 34.2
1 Feb 205.0 23.0 28.2
2 Mar 224.0 28.0 28.0
3 Apr 242.0 35.0 25.5
4 May 235.0 39.0 19.8

Question 1: What is the trend of sales? (Line chart)​

plt.figure(figsize=(8, 4))
plt.plot(df["month"], df["sales"], marker="o", color="#A4457A", linewidth=2)
plt.title("Monthly sales in 2025")
plt.ylabel("Sales (thousand Rs.)")
plt.grid(True, alpha=0.3)
plt.show()
OUTPUT (chart)​
Question 1: What is the trend of sales? (Line chart): Monthlysalesin2025 320 300 Sales (thousand Rs.) 280 260 240 220 200 Mar May Jan Feb Apr jun jul Aug Sep Oct Nov Dec
Question 1: What is the trend of sales? (Line chart): Monthlysalesin2025 320 300 Sales (thousand Rs.) 280 260 240 220 200 Mar May Jan Feb Apr jun jul Aug Sep Oct Nov Dec

Question 2: Does spending more on ads increase sales? (Scatter)

plt.figure(figsize=(6.5, 4))
plt.scatter(df["ads_budget"], df["sales"], color="#6B5B95", s=70)
plt.title("Relationship between ads budget and sales")
plt.xlabel("Ads budget (thousand Rs.)")
plt.ylabel("Sales (thousand Rs.)")
plt.show()
OUTPUT (chart)​
Question 1: What is the trend of sales? (Line chart): Relationshipbetweenadsbudgetandsales 320 300 Sales (thousand Rs.) 280 260 240 220 200 20 30 35 40 45 50 55 60 Ads budget (thousand Rs.)
Question 1: What is the trend of sales? (Line chart): Relationshipbetweenadsbudgetandsales 320 300 Sales (thousand Rs.) 280 260 240 220 200 20 30 35 40 45 50 55 60 Ads budget (thousand Rs.)

Question 3: In which month was the profit highest and lowest? (Bar)​

best = df["profit"].idxmax()
worst = df["profit"].idxmin()
colors = ["#A4457A" if i == best else "#2F7D4F" if i == worst else "#D9D9E3" for i in
df.index]
plt.figure(figsize=(8, 4))
plt.bar(df["month"], df["profit"], color=colors)
plt.title("Monthly profit (pink = highest, green = lowest)")
plt.ylabel("Profit (thousand Rs.)")
plt.show()
print("Highest profit:", df.loc[best, "month"], "|", "Lowest:", df.loc[worst, "month"])
OUTPUT (chart)​
Question 3: In which month was the profit highest and lowest? (Bar): Monthlyprofit(pink=highest,green=lowest) 35 30 Profit (thousand Rs.) 25 20 15 10 Mar Apr May Aug Feb jul Jan jun Sep Oct Nov Dec
Question 3: In which month was the profit highest and lowest? (Bar): Monthlyprofit(pink=highest,green=lowest) 35 30 Profit (thousand Rs.) 25 20 15 10 Mar Apr May Aug Feb jul Jan jun Sep Oct Nov Dec
GOOD PRACTICE​

In real work, do not keep all the bars in one colour. Give a highlight colour to the thing you want to show (highest/lowest) and keep the rest light (grey). This way the viewer understands immediately.

Plotting directly with Pandas​

Writing .plot() on a Pandas DataFrame makes a Matplotlib chart directly, with less code.

df.plot(x="month", y=["sales", "profit"], kind="line", marker="o", figsize=(8, 4),
title="Sales and profit")
plt.ylabel("Thousand Rs.")
plt.show()
OUTPUT (chart)​
Plotting directly with Pandas: Sales andprofit sales 300 profit 250 Thousand Rs. 200 150 100 50 Mar May jul Jan Sep Nov month
Plotting directly with Pandas: Sales andprofit sales 300 profit 250 Thousand Rs. 200 150 100 50 Mar May jul Jan Sep Nov month

6 principles of a good chart​

  1. The title says what the chart shows, and the axis labels carry units (Rs., kg, %).

  2. Choose the right chart (line for trend, bar for comparison, scatter for relationship).

  3. Always start the y-axis of a bar chart at 0. Otherwise even a small difference looks very big (see below).

  4. Use few colours and use them with meaning (highlight). Do not keep more than 5 slices in a pie chart.

  5. One point per chart. If you put in too many things, nothing will be understood.

  6. Ask the chart yourself: "if I knew nothing about this, would I understand it?"

values = [96, 100]
names = ["Product A", "Product B"]
fig, axes = plt.subplots(1, 2, figsize=(8, 3.4))
axes[0].bar(names, values, color="#6B5B95")
axes[0].set_ylim(94, 101)
axes[0].set_title("Misleading: y-axis starts at 94")
axes[1].bar(names, values, color="#2F7D4F")
axes[1].set_ylim(0, 110)
axes[1].set_title("Correct: y-axis starts at 0")
plt.tight_layout()
plt.show()
OUTPUT (chart)​
6 principles of a good chart: Misleading: y-axis starts at 94 Correct: y-axis starts at o 101 100 100 99 80 98 60 97 40 96 95 20 94 Product A Product B Product A Product B
6 principles of a good chart: Misleading: y-axis starts at 94 Correct: y-axis starts at o 101 100 100 99 80 98 60 97 40 96 95 20 94 Product A Product B Product A Product B

Both charts have the same data (96 and 100). In the first chart B looks several times bigger than A, whereas the difference is only 4%. Charts like this mislead people.

7.8 Hands-on with Matplotlib​

Do these exercises on the df of 7.7 (12 months of sales).

  1. Line chart: make the trend of ads_budget, with a title and labels.

  2. Histogram: make the distribution of sales (bins=6).

  3. Bar chart: make a bar chart of the profit of each month, with the months whose profit is below 30 in red.

  4. Dual chart: draw the lines of both sales and ads_budget in one chart (with a legend).

  5. Subplots: make a line, a bar and a scatter side by side in 1 row and 3 columns, and save it with savefig .

First make them yourself, then compare by changing the code of 7.7. Writing a conclusion in two sentences after looking at the charts is also compulsory practice (for example: "Sales have grown as ads have increased").

KEY TAKEAWAYS​
  • A chart tells the story at a glance. A Data Scientist must be able to explain things with charts.

  • Two ways of using Matplotlib: pyplot (plt.plot) and Object-Oriented (fig, ax = plt.subplots()).

  • Line = trend, Bar = comparison, Histogram = distribution, Scatter = relationship between two things, Box = spread and outliers.

  • Customization: title, xlabel, ylabel, color, marker, linestyle, alpha, legend, grid, figsize.

  • Subplots put many charts in one figure, tight_layout() prevents collisions, savefig() saves.

  • Start a bar chart's y-axis at 0, use colour with meaning, and explain your point with a highlight.

  • df.plot() makes a Matplotlib chart directly from Pandas.