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.
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.
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.
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.
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.
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
- What are grid lines in Matplotlib?
- Which function is used to configure grid lines?
- How can you enable grid lines?
- How can you disable grid lines?
- What is the purpose of the axis parameter?
- How can you change the grid line color?
- Which parameter controls grid line transparency?
- What is the difference between major and minor grid lines?
- How can you display only Y-axis grid lines?
- 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.colorchanges the grid color.linestylechanges the grid line pattern.linewidthchanges line thickness.alphacontrols 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.