Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Grid Lines in Matplotlib

Learn how to add grid lines to Matplotlib charts, control their visibility, customize line styles, and improve chart readability using different grid options.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand grid lines in Matplotlib.
  • Add grid lines to charts using grid().
  • Enable or disable grid lines.
  • Display grid lines on the X-axis and Y-axis separately.
  • Customize grid color, line style, and line width.
  • Control major and minor grid lines.
  • Use grid lines with the object-oriented API.

2. Introduction to Grid Lines

Grid lines are horizontal and vertical reference lines displayed inside a chart. They help users understand the position and value of data points more easily.

When a chart contains multiple values, grid lines make it easier to compare data and estimate values from the axes.

Why Do We Use Grid Lines?

  • To improve chart readability.
  • To compare data values easily.
  • To identify approximate positions of data points.
  • To make charts easier to understand.

Basic Syntax

plt.grid()

The grid() function is used to configure grid lines in a Matplotlib chart.

3. Adding Basic Grid Lines

You can add grid lines to a chart by calling plt.grid(True).

Example: Line Chart with Grid Lines

import matplotlib.pyplot as plt

months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 130, 180, 200, 220]

plt.plot(months, sales, marker="o")

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.grid(True)

plt.show()

Expected Output

Chart Title: Monthly Sales

X-axis: Month
Y-axis: Sales

Line:
Monthly sales values

Grid:
Horizontal and vertical grid lines are displayed.

Markers:
Circular markers appear on each data point.
Tip: Use plt.grid(True) when you want to make grid lines visible in your chart.

4. Enabling and Disabling Grid Lines

You can enable or disable grid lines by passing True or False to the grid() function.

Example: Enable Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)

plt.grid(True)

plt.title("Grid Enabled")

plt.show()

Expected Output

Chart Title: Grid Enabled

Grid Lines:
Visible

Both horizontal and vertical grid lines
are displayed in the plotting area.

Example: Disable Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y)

plt.grid(False)

plt.title("Grid Disabled")

plt.show()

Expected Output

Chart Title: Grid Disabled

Grid Lines:
Hidden

The chart displays the plotted line
without grid lines.
Tip: Use False when you want a clean chart without reference lines.

5. Grid Lines for Specific Axes

Matplotlib allows you to display grid lines for the X-axis or Y-axis separately using the axis parameter.

Axis Value Description
both Displays grid lines for both axes.
x Displays grid lines along the X-axis ticks.
y Displays grid lines along the Y-axis ticks.

Example: X-axis Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y, marker="o")

plt.grid(True, axis="x")

plt.title("X-axis Grid Lines")

plt.show()

Expected Output

Chart Title: X-axis Grid Lines

Grid:
Vertical reference lines are displayed
at X-axis tick positions.

Horizontal grid lines:
Not displayed.

Example: Y-axis Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.plot(x, y, marker="o")

plt.grid(True, axis="y")

plt.title("Y-axis Grid Lines")

plt.show()

Expected Output

Chart Title: Y-axis Grid Lines

Grid:
Horizontal reference lines are displayed
at Y-axis tick positions.

Vertical grid lines:
Not displayed.

6. Customizing Grid Lines

You can customize grid lines by changing their color, line style, and line width.

Common Grid Parameters

Parameter Description Example
color Changes grid line color. "gray"
linestyle Changes the grid line pattern. "--"
linewidth Changes grid line thickness. 0.7
alpha Controls grid line transparency. 0.5

Example: Customized Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 25, 30, 45, 50]

plt.plot(x, y, marker="o")

plt.grid(
    True,
    color="gray",
    linestyle="--",
    linewidth=0.7,
    alpha=0.6
)

plt.title("Customized Grid Lines")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Chart Title: Customized Grid Lines

Grid Color: Gray
Line Style: Dashed
Line Width: 0.7
Transparency: 0.6

The chart displays customized dashed grid lines.
Tip: Use light and transparent grid lines so they do not distract users from the actual data.

7. Different Grid Line Styles

You can use different line styles to change the appearance of grid lines.

Line Style Value Description
Solid - Continuous line.
Dashed -- Dashed line.
Dotted : Dotted line.
Dash-dot -. Combination of dashes and dots.

Example: Dashed Grid Lines

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [5, 15, 25, 35, 45]

plt.plot(x, y)

plt.grid(
    True,
    linestyle="--"
)

plt.title("Dashed Grid Lines")

plt.show()

Expected Output

Chart Title: Dashed Grid Lines

Grid Style:
Dashed

The chart displays dashed horizontal
and vertical grid lines.

8. Major and Minor Grid Lines

Matplotlib supports major and minor ticks. You can use these ticks to display different levels of grid lines.

  • Major Grid Lines: Reference lines associated with major tick positions.
  • Minor Grid Lines: Additional reference lines associated with minor tick positions.

Example: Major and Minor Grid Lines

import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

fig, ax = plt.subplots()

ax.plot(x, y, marker="o")

ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_minor_locator(AutoMinorLocator())

ax.grid(
    True,
    which="major",
    linestyle="-",
    linewidth=0.8
)

ax.grid(
    True,
    which="minor",
    linestyle=":",
    linewidth=0.5
)

ax.set_title("Major and Minor Grid Lines")

plt.show()

Expected Output

Chart Title: Major and Minor Grid Lines

Major Grid:
Solid grid lines at major tick positions.

Minor Grid:
Dotted grid lines at minor tick positions.

Both levels of grid lines are displayed
in the same chart.
Important: Minor grid lines may not appear unless minor tick positions are configured. Use AutoMinorLocator() to create automatic minor tick positions for suitable linear axes.

9. Grid Lines Using Object-Oriented API

Matplotlib also supports grid configuration through the object-oriented API. You can call ax.grid() on an Axes object.

Example

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

ax.plot(x, y, marker="o")

ax.set_title("Object-Oriented Grid Example")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

ax.grid(
    True,
    color="gray",
    linestyle="--",
    alpha=0.5
)

plt.show()

Expected Output

Chart Title: Object-Oriented Grid Example

X-axis: X Values
Y-axis: Y Values

Grid:
Enabled using ax.grid()

Grid Style:
Gray dashed lines with transparency.
Tip: Use ax.grid() when working with multiple subplots or when using the object-oriented API.

10. Practical Activity

Task: Create a Monthly Temperature Chart

Create a line chart to display the average temperature recorded over six months.

Given Data:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

temperature = [18, 21, 25, 30, 34, 32]

Requirements:

  • Create a line chart using the given data.
  • Add markers to the line.
  • Set the title to Monthly Temperature.
  • Add X-axis and Y-axis labels.
  • Enable grid lines.
  • Use dashed grid lines.
  • Set grid color to gray.
  • Set grid transparency to 0.5.

11. Practice Questions

  1. What are grid lines in Matplotlib?
  2. Which function is used to configure grid lines?
  3. How can you enable grid lines?
  4. How can you disable grid lines?
  5. What is the purpose of the axis parameter?
  6. How can you change the grid line color?
  7. Which parameter controls grid line transparency?
  8. What is the difference between major and minor grid lines?
  9. How can you display only Y-axis grid lines?
  10. What is the difference between plt.grid() and ax.grid()?

12. Lesson Summary

In this lesson, you learned how to add and customize grid lines in Matplotlib. Grid lines improve chart readability and help users compare data values.

  • plt.grid(True) enables grid lines.
  • plt.grid(False) disables grid lines.
  • axis="x" configures X-axis grid lines.
  • axis="y" configures Y-axis grid lines.
  • color changes the grid color.
  • linestyle changes the grid line pattern.
  • linewidth changes line thickness.
  • alpha controls transparency.
  • which="major" configures major grid lines.
  • which="minor" configures minor grid lines.
  • ax.grid() works with the object-oriented API.

You are now ready to use grid lines to create clean, readable, and professional Matplotlib charts.