Skip to content
C

Matplotlib

Complete learning notes


1. Introduction

Numbers in a table can be hard to interpret at a glance — but a well-made chart can reveal patterns instantly. Matplotlib is Python's foundational plotting library, used to turn raw data into visual charts like line plots, bar charts, and scatter plots. Visualizing data is a critical step in understanding it before (and after) building any ML model.


2. What is Matplotlib?

Simple definition: Matplotlib is a Python library used to create charts and graphs — such as line plots, bar charts, and scatter plots — to visualize data.

Technical explanation: Matplotlib is a plotting library that provides a flexible, object-based API (commonly accessed through its pyplot module) for generating a wide range of static, publication-quality visualizations from numerical or tabular data.


3. Why is it Important?

  • Visualizing data helps you spot patterns, trends, and outliers that are hard to notice in raw numbers.
  • ML workflows use plots to understand data before modeling, and to evaluate model performance afterward (e.g., plotting errors over time).
  • Charts communicate insights far more effectively to others than tables of numbers.

4. Prerequisites

You should be comfortable with Python basics, NumPy, and ideally Pandas, since data for plotting often comes from arrays or DataFrames.


5. Core Concepts

  1. Importing pyplot (import matplotlib.pyplot as plt)
  2. Line plots
  3. Bar charts
  4. Scatter plots
  5. Histograms
  6. Titles, axis labels, and legends
  7. Displaying and saving plots

6. Detailed Explanation

a) Importing pyplot

Most Matplotlib usage happens through its pyplot module, conventionally imported as plt.

b) Line Plots

plt.plot(x, y) draws a line connecting data points — ideal for showing trends over time or continuous relationships.

c) Bar Charts

plt.bar(categories, values) draws bars — ideal for comparing values across distinct categories.

d) Scatter Plots

plt.scatter(x, y) draws individual points without connecting them — ideal for showing the relationship between two numeric variables.

e) Histograms

plt.hist(data) groups numeric data into "bins" and shows how many values fall into each bin — ideal for understanding the distribution/spread of a dataset.

f) Titles, Labels, and Legends

  • plt.title("...") adds a chart title.
  • plt.xlabel("...") and plt.ylabel("...") label the axes.
  • plt.legend() displays labels for multiple plotted series, so viewers know what each line or bar represents.

g) Displaying and Saving Plots

plt.show() displays the chart. plt.savefig("filename.png") saves the chart as an image file.


7. How It Works

  1. You provide Matplotlib with your data (usually as lists or NumPy arrays).
  2. You choose a plot type (plot, bar, scatter, hist) matching what you want to show.
  3. You add titles, labels, and a legend to make the chart understandable.
  4. plt.show() renders the final chart on your screen (or plt.savefig() saves it to a file).

8. Real-World Example

Imagine tracking your monthly expenses. A table of 12 numbers is hard to interpret quickly, but a line plot instantly shows you whether your spending is rising, falling, or staying steady across the year — the same principle applies to tracking a model's error decreasing during training.


9. Technical Example

python
import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] sales = [200, 250, 220, 300] plt.plot(months, sales) plt.title("Monthly Sales") plt.xlabel("Month") plt.ylabel("Sales") plt.show()

This creates a simple line chart showing how sales changed across four months, with clear labels for context.


10. Python Example

python
import matplotlib.pyplot as plt # Line plot - showing a trend over time months = ["Jan", "Feb", "Mar", "Apr", "May"] sales = [200, 250, 220, 300, 280] plt.plot(months, sales, marker="o", label="Sales") plt.title("Monthly Sales Trend") plt.xlabel("Month") plt.ylabel("Sales (in units)") plt.legend() plt.show() # Bar chart - comparing categories subjects = ["Math", "Science", "English"] scores = [85, 78, 92] plt.bar(subjects, scores, color="skyblue") plt.title("Scores by Subject") plt.xlabel("Subject") plt.ylabel("Score") plt.show() # Scatter plot - relationship between two variables study_hours = [1, 2, 3, 4, 5] marks = [40, 50, 65, 70, 90] plt.scatter(study_hours, marks, color="green") plt.title("Study Hours vs Marks") plt.xlabel("Study Hours") plt.ylabel("Marks") plt.show() # Histogram - showing distribution of data ages = [18, 21, 22, 19, 25, 30, 21, 22, 24, 29] plt.hist(ages, bins=5, color="orange", edgecolor="black") plt.title("Age Distribution") plt.xlabel("Age") plt.ylabel("Frequency") plt.show()

Expected Output:

Running this code opens four separate chart windows (or renders four inline plots in a notebook):

  1. A line chart showing sales rising and dipping across five months, with labeled markers.
  2. A bar chart comparing scores across three subjects.
  3. A scatter plot showing an upward trend between study hours and marks.
  4. A histogram showing how ages are grouped into 5 ranges (bins).

11. Code Explanation

  • plt.plot(months, sales, marker="o", label="Sales") draws a line connecting the sales values, with circular markers at each data point, and assigns a label for the legend.
  • plt.legend() displays a small box identifying which line/data corresponds to the given label.
  • plt.bar(subjects, scores, color="skyblue") draws one bar per subject, with height representing the score.
  • plt.scatter(study_hours, marks, color="green") plots individual points without connecting them, helping visualize the relationship between two variables.
  • plt.hist(ages, bins=5, ...) divides the age values into 5 equally-sized ranges and counts how many values fall into each range.
  • plt.title(), plt.xlabel(), and plt.ylabel() each add readable context so anyone viewing the chart understands what it represents.
  • plt.show() is required at the end of each plot to actually render and display it.

12. Advantages

  • Highly flexible — supports nearly every common chart type.
  • Works seamlessly with NumPy arrays and Pandas DataFrames.
  • Widely used, well-documented, and a foundation for other libraries like Seaborn.
  • Produces publication-quality static images.

13. Limitations

  • Default chart styling can look plain compared to newer libraries like Seaborn.
  • Writing highly customized plots can require verbose code.
  • Not designed for interactive, web-based dashboards out of the box (other libraries handle that).

14. Common Mistakes

  • Forgetting to call plt.show(), so the chart never actually displays.
  • Mixing up which plot type suits the data — e.g., using a line plot for unordered categories instead of a bar chart.
  • Not labeling axes or adding a title, making the chart confusing to interpret later.
  • Forgetting plt.legend() when plotting multiple series, making it unclear which line is which.

15. Best Practices

  • Always include a title and axis labels for clarity.
  • Choose the chart type that matches your data: line for trends, bar for categories, scatter for relationships, histogram for distributions.
  • Use plt.legend() whenever a chart has more than one labeled series.
  • Keep charts simple and focused — avoid cramming too much information into a single plot.

16. Real-World Applications

  • Visualizing sales trends, stock prices, or sensor readings over time.
  • Exploring relationships between features before building an ML model (e.g., study hours vs marks).
  • Plotting a model's training error over time to check if it's improving.

17. Interview-Oriented Points

  • Be ready to explain when to use a line plot vs a bar chart vs a scatter plot.
  • Understand what a histogram shows (distribution/frequency of values).
  • Know the basic Matplotlib workflow: prepare data → choose plot type → add labels/title → plt.show().

18. Exam-Oriented Points

  • Matplotlib's pyplot module (commonly plt) is used for most plotting tasks.
  • plot() = line chart, bar() = bar chart, scatter() = scatter plot, hist() = histogram.
  • title(), xlabel(), ylabel(), and legend() add context to a chart.
  • show() displays the chart; savefig() saves it as an image file.

19. Comparison Table — Line Plot vs Bar Chart vs Scatter Plot vs Histogram

Chart TypeBest Used ForExample Use Case
Line PlotShowing trends over a continuous sequence (like time)Sales over months
Bar ChartComparing values across distinct categoriesScores across different subjects
Scatter PlotShowing the relationship between two numeric variablesStudy hours vs marks
HistogramShowing the distribution/spread of a single numeric variableAge distribution of a group

20. Quick Revision

  • Matplotlib's pyplot module (plt) is the standard tool for creating charts in Python.
  • Key plot types: plot() (line), bar(), scatter(), hist().
  • Always add title(), xlabel(), ylabel(), and legend() for clarity.
  • plt.show() displays a chart; plt.savefig() saves it as a file.
  • Choose the chart type based on what you want to reveal: trend, comparison, relationship, or distribution.

Mock Test

  • Matplotlib — Quick Test

    A 10-question multiple-choice check on Matplotlib.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems