Matplotlib Grid
In Matplotlib, grids help to make plots easier to read by adding horizontal and vertical lines along the axes. Grids provide visual cues for aligning points on the plot with their corresponding x and y values. You can control the appearance and behavior of the grid lines, including their visibility, style, color, and location.
Here’s how to use and customize grids in Matplotlib.
1. Basic Grid
To add a basic grid to your plot, use plt.grid(True):
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot
plt.plot(x, y)
# Add grid
plt.grid(True)
plt.show()
This will add a default grid to the plot with both vertical and horizontal grid lines.
2. Control Grid Visibility
You can enable or disable grid lines along the x-axis and y-axis individually by passing axis='x' or axis='y' to the grid() function.
plt.plot(x, y)
# Add grid only on the y-axis
plt.grid(True, axis='y')
plt.show()
This will display the grid lines only along the y-axis.
3. Customizing Grid Line Style
You can customize the appearance of the grid lines by specifying parameters such as line style, color, and width.
1. Line Style
The grid line style can be customized using the linestyle argument.
plt.plot(x, y)
# Add grid with dashed lines
plt.grid(True, linestyle='--')
plt.show()
Available line styles:
- Solid:
'-' - Dashed:
'--' - Dotted:
':' - Dash-dot:
'-.'
2. Grid Line Color
You can change the color of the grid lines using the color argument.
plt.plot(x, y)
# Add grid with red lines
plt.grid(True, color='red')
plt.show()
3. Grid Line Width
You can change the width of the grid lines using the linewidth (or lw) argument.
plt.plot(x, y)
# Add grid with thicker lines
plt.grid(True, linewidth=2)
plt.show()
4. Grid Line Alpha (Transparency)
You can make the grid lines transparent or semi-transparent by adjusting the alpha argument, which takes a value between 0 (completely transparent) and 1 (fully opaque).
plt.plot(x, y)
# Add grid with semi-transparent lines
plt.grid(True, color='blue', alpha=0.5)
plt.show()
5. Major and Minor Grid Lines
Matplotlib distinguishes between major and minor ticks. You can display grid lines for both major and minor ticks independently.
1. Major Grid Lines
By default, plt.grid(True) affects the major ticks. If you want to customize major grid lines:
plt.plot(x, y)
# Major grid lines
plt.grid(True, which='major', color='black', linestyle='-')
plt.show()
2. Minor Grid Lines
To enable and customize minor grid lines, you need to specify the minor ticks first using plt.minorticks_on().
plt.plot(x, y)
# Turn on minor ticks
plt.minorticks_on()
# Add minor grid lines
plt.grid(True, which='minor', color='gray', linestyle=':', alpha=0.7)
# Add major grid lines
plt.grid(True, which='major', color='black', linestyle='-', linewidth=1.5)
plt.show()
You can control the appearance of both the major and minor grid lines using the which argument, with possible values:
'major': Controls the major grid lines (default).'minor': Controls the minor grid lines.
6. Grids in Subplots
You can add grids to each subplot independently when creating multiple subplots.
# Create subplots
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.grid(True) # Grid for the first subplot
plt.subplot(2, 1, 2)
plt.plot(x, [i*2 for i in y])
plt.grid(True, linestyle='--', color='green') # Grid for the second subplot
plt.tight_layout()
plt.show()
In this example, each subplot has its own grid configuration.
7. Grid for Logarithmic Scale Plots
You can also add grids to plots that use logarithmic scaling. The grid will adjust to the logarithmic scale.
import numpy as np
# Data
x = np.linspace(1, 100, 100)
y = np.exp(x)
# Logarithmic y-axis
plt.plot(x, y)
plt.yscale('log')
# Add grid
plt.grid(True)
plt.show()
8. Grid Line Positioning (Behind or In Front of Plot)
By default, grid lines are drawn behind the plot elements. You can change their position using plt.gca().set_axisbelow().
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot
plt.plot(x, y)
# Make grid appear in front of the plot
plt.gca().set_axisbelow(False)
plt.grid(True)
plt.show()
To make the grid appear behind the plot (default), use:
plt.gca().set_axisbelow(True)
9. Removing the Grid
To remove the grid from a plot, you can call plt.grid(False).
plt.plot(x, y)
# Disable grid
plt.grid(False)
plt.show()
Summary of Grid Customization Options
- Enable/Disable Grid:
plt.grid(True)orplt.grid(False) - Axis:
plt.grid(True, axis='x')(for x-axis only) oraxis='y'(for y-axis only) - Line Style:
linestyle='--',linestyle=':', etc. - Color:
color='red',color='#00FF00', etc. - Line Width:
linewidth=2 - Transparency (Alpha):
alpha=0.5 - Major vs Minor Grid:
which='major'orwhich='minor' - Behind/Front of Plot:
plt.gca().set_axisbelow(True/False)
Conclusion
Grids in Matplotlib are highly customizable, allowing you to add clear visual guides to your plots and enhance readability. You can control the grid’s style, color, transparency, line width, and visibility for major and minor ticks, ensuring that your plots are visually appealing and easy to interpret.