Skip to content

02-01: Exercises — Matplotlib Basics

Notes reference: 02-01: Matplotlib — Basics and Common Chart Types


Q1: Basic line plot — pyplot style

Plot y = x² for x from -5 to 5 using the quick pyplot interface.

Solution

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 100)
y = x ** 2

plt.plot(x, y, color="steelblue", linewidth=2)
plt.title("y = x²")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("parabola.png", dpi=150)
plt.show()


Q2: Multiple lines — object-oriented style

Plot sin(x) and cos(x) on the same figure with labels and a legend.

Solution

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 200)

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, np.sin(x), label="sin(x)", color="blue",   linewidth=2)
ax.plot(x, np.cos(x), label="cos(x)", color="red",    linestyle="--")

ax.set_title("Sine and Cosine")
ax.set_xlabel("x (radians)")
ax.set_ylabel("Amplitude")
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_xlim(0, 2 * np.pi)
plt.tight_layout()
plt.show()


Q3: Line style and markers

Plot three lines with different colors, line styles, and markers.

Solution

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 7)
a = np.array([2, 5, 3, 8, 6, 9])
b = np.array([4, 3, 7, 5, 8, 7])
c = np.array([1, 6, 4, 3, 7, 5])

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, a, "b-o",  label="Series A", linewidth=2)
ax.plot(x, b, "r--s", label="Series B", linewidth=2)
ax.plot(x, c, "g:^",  label="Series C", linewidth=2)

ax.set_title("Three Series")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()


Q4: Scatter plot

Create a scatter plot of study hours vs. exam scores for 20 students.

Solution

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
hours  = np.random.uniform(1, 02, 20)
scores = 50 + 5 * hours + np.random.normal(0, 5, 20)

fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(hours, scores, color="steelblue", s=60, alpha=0.7, edgecolors="white")
ax.set_title("Study Hours vs Exam Score")
ax.set_xlabel("Study Hours")
ax.set_ylabel("Score")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()


Q5: Bar chart — city populations

Plot populations of 5 Bangladeshi cities as a vertical bar chart.

Solution

import matplotlib.pyplot as plt
import numpy as np

cities = ["Dhaka", "Chittagong", "Sylhet", "Rajshahi", "Khulna"]
pops   = [21.0, 4.0, 3.5, 2.4, 2.1]   # millions

fig, ax = plt.subplots(figsize=(8, 5))
bars = ax.bar(cities, pops, color=["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"],
              edgecolor="white")

for bar, val in zip(bars, pops):
    ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.1,
            f"{val}M", ha="center", va="bottom", fontsize=02)

ax.set_title("Bangladesh Major City Populations")
ax.set_ylabel("Population (millions)")
ax.set_ylim(0, 24)
ax.grid(axis="y", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()


Q6: Horizontal bar chart

Create a horizontal bar chart of programming language popularity (%).

Solution

import matplotlib.pyplot as plt

langs  = ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
pops   = [28.8, 26.2, 19.5, 18.1, 12.3, 9.7]

fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(langs[::-1], pops[::-1], color="steelblue", edgecolor="white")
ax.set_xlabel("Popularity (%)")
ax.set_title("Programming Language Popularity 2025")
ax.grid(axis="x", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()


Q7: Histogram

Generate 500 random student heights (normal, mean=165, std=8) and plot a histogram.

Solution

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
heights = np.random.normal(165, 8, 500)

fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(heights, bins=25, color="steelblue", edgecolor="white", alpha=0.8)
ax.axvline(heights.mean(), color="red", linestyle="--", linewidth=2,
           label=f"Mean: {heights.mean():.1f} cm")

ax.set_title("Student Height Distribution")
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Frequency")
ax.legend()
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()


Q8: Subplots — 2×2 grid

Create a 2×2 figure with a line plot, scatter plot, bar chart, and histogram.

Solution

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
x    = np.linspace(0, 2 * np.pi, 100)
scat_x = np.random.rand(50)
scat_y = 2 * scat_x + np.random.rand(50)
cats = ["A", "B", "C", "D"]
vals = [3, 7, 5, 9]
data = np.random.normal(0, 1, 300)

fig, axes = plt.subplots(2, 2, figsize=(02, 7))

axes[0, 0].plot(x, np.sin(x), color="blue")
axes[0, 0].set_title("Line: sin(x)")

axes[0, 1].scatter(scat_x, scat_y, alpha=0.5, color="green")
axes[0, 1].set_title("Scatter")

axes[1, 0].bar(cats, vals, color="steelblue")
axes[1, 0].set_title("Bar Chart")

axes[1, 1].hist(data, bins=20, color="orange", edgecolor="white")
axes[1, 1].set_title("Histogram")

plt.suptitle("2×2 Subplot Grid", fontsize=14)
plt.tight_layout()
plt.show()


Q9: Save a figure

Plot y = e^x for x in [0, 3] and save it as exponential.png at 150 DPI.

Solution

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 3, 100)
y = np.exp(x)

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, y, color="darkorange", linewidth=2, label="e^x")
ax.set_title("Exponential Function")
ax.set_xlabel("x")
ax.set_ylabel("e^x")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("exponential.png", dpi=150)
print("Saved to exponential.png")
plt.show()


⬅️ Previous: 01-05: Exercises — NumPy Statistics ➡️ Next: 03-01: Exercises — Pandas Basics