CS Pathfinder Logo CS Pathfinder

Unit 5 · Advanced Topics

Introduction to Matplotlib

Matplotlib is the most widely-used plotting library in Python, providing a comprehensive set of tools for creating static, animated, and interactive visualizations. It is the foundation upon which other visualization libraries like Seaborn are built.

Table of Contents

University Definition

Matplotlib is an open-source 2D plotting library for Python that produces publication-quality figures in a variety of formats. Its pyplot module provides a MATLAB-like interface for creating plots, histograms, bar charts, scatter plots, and more with just a few lines of code.

Installation & Import

# Install (in terminal)
pip install matplotlib

# Import
import matplotlib.pyplot as plt
import numpy as np

1. Line Plot

A line plot is the most basic chart type, used to visualize trends over time or continuous data.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y, marker="o", color="blue", linestyle="--")
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()

Multiple Lines on One Plot

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5, 6, 7]
temp_delhi = [35, 37, 38, 36, 34, 33, 35]
temp_mumbai = [30, 31, 33, 32, 31, 30, 29]

plt.plot(days, temp_delhi, label="Delhi", color="red", marker="o")
plt.plot(days, temp_mumbai, label="Mumbai", color="blue", marker="s")
plt.title("Temperature Comparison")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(True)
plt.show()

2. Bar Chart

Bar charts are used to compare categorical data. Each bar represents a category and its height represents the value.

import matplotlib.pyplot as plt

students = ["Amit", "Priya", "Rahul", "Sneha"]
marks = [85, 92, 78, 95]
colors = ["skyblue", "salmon", "lightgreen", "gold"]

plt.bar(students, marks, color=colors, edgecolor="black")
plt.title("Student Marks - Bar Chart")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.ylim(0, 100)

# Add value labels on bars
for i, v in enumerate(marks):
    plt.text(i, v + 1, str(v), ha="center", fontweight="bold")

plt.show()

Horizontal Bar Chart

plt.barh(students, marks, color="teal")
plt.title("Horizontal Bar Chart")
plt.xlabel("Marks")
plt.show()

3. Histogram

A histogram displays the frequency distribution of continuous data by grouping data into bins.

import matplotlib.pyplot as plt
import numpy as np

# Generate random marks for 100 students
marks = np.random.randint(30, 100, 100)

plt.hist(marks, bins=10, color="steelblue",
         edgecolor="black", alpha=0.7)
plt.title("Marks Distribution - Histogram")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.grid(axis="y", alpha=0.3)
plt.show()

4. Scatter Plot

Scatter plots show the relationship between two numerical variables. Each point represents an observation.

import matplotlib.pyplot as plt
import numpy as np

hours_studied = [2, 4, 6, 8, 3, 5, 7, 9, 1, 10]
marks = [30, 55, 70, 88, 40, 65, 75, 92, 20, 98]

plt.scatter(hours_studied, marks, color="red", s=100, edgecolor="black")
plt.title("Hours Studied vs Marks Obtained")
plt.xlabel("Hours Studied")
plt.ylabel("Marks")
plt.grid(True, alpha=0.3)
plt.show()

5. Pie Chart

Pie charts show the proportion of each category relative to the whole.

import matplotlib.pyplot as plt

languages = ["Python", "Java", "C++", "JavaScript"]
usage = [35, 25, 20, 20]
colors = ["#3498db", "#e74c3c", "#2ecc71", "#f39c12"]
explode = [0.1, 0, 0, 0]  # Explode first slice

plt.pie(usage, labels=languages, colors=colors,
        explode=explode, autopct="%1.1f%%",
        shadow=True, startangle=140)
plt.title("Programming Language Usage")
plt.show()

6. Subplots & Saving Plots

Subplots allow multiple plots in a single figure. Use plt.subplot() or plt.subplots().

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10)
y1 = x ** 2
y2 = np.sqrt(x) * 3
y3 = np.sin(x)
y4 = np.cos(x)

# Create 2x2 subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

axes[0, 0].plot(x, y1, "r-o")
axes[0, 0].set_title("y = x²")

axes[0, 1].plot(x, y2, "b-s")
axes[0, 1].set_title("y = √x × 3")

axes[1, 0].plot(x, y3, "g-^")
axes[1, 0].set_title("y = sin(x)")

axes[1, 1].plot(x, y4, "m-d")
axes[1, 1].set_title("y = cos(x)")

plt.tight_layout()
plt.show()

# Save plot to file
plt.savefig("plots.png", dpi=300, bbox_inches="tight")

Chart Types — Quick Reference

Chart Type Function Best For Key Parameters
Lineplt.plot()Trends over timemarker, color, linestyle
Barplt.bar()Categorical comparisoncolor, edgecolor, width
Histogramplt.hist()Frequency distributionbins, alpha, edgecolor
Scatterplt.scatter()Correlation between 2 variabless, c, edgecolor, alpha
Pieplt.pie()Proportions of a wholelabels, autopct, explode

Common Mistakes

  • Forgetting plt.show() — the plot won't appear on screen.
  • Not calling plt.figure() before multiple separate plots — they overlap.
  • Using plt.savefig() before plt.show() — the file may be blank. Call savefig first.
  • Not importing NumPy when generating data for plots.
  • Confusing plt.subplot() (single plot) with plt.subplots() (returns axes array).

University Exam Tip

University exams frequently ask: "Write a program to plot a bar chart / histogram / pie chart using Matplotlib". Practice all 5 chart types. Always include title(), xlabel(), ylabel(), and show(). Mention savefig() for saving plots to files.

Key Points

pyplot is the most commonly used module — import as plt.

plot() → line, bar() → bar chart, hist() → histogram, scatter() → scatter, pie() → pie chart.

Always call plt.show() to display the plot.

Use plt.title(), plt.xlabel(), plt.ylabel(), plt.legend() for labels.

plt.subplot() or plt.subplots() creates multiple plots in one figure.

plt.savefig() saves plots as PNG, JPG, SVG, or PDF files.

Practice Questions

  1. Plot a line graph of temperature data for 7 days with proper labels and legend.
  2. Create a bar chart comparing marks of 5 students in 3 subjects.
  3. Generate a histogram of random marks for 200 students.
  4. Create a scatter plot showing correlation between study hours and marks.
  5. Plot a pie chart showing time spent on different activities in a day.
  6. Create a 2×2 subplot figure with line, bar, scatter, and histogram charts.

Summary

Matplotlib is essential for data visualization in Python. Master the five basic chart types (line, bar, histogram, scatter, pie), labeling, legends, subplots, and saving plots. Combined with NumPy and Pandas, it forms the complete data science toolkit.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.