0
0
Matplotlibdata~5 mins

Grid lines configuration in Matplotlib

Choose your learning style9 modes available
Introduction

Grid lines help you see the values on a chart more clearly. They make it easier to compare points and understand the data.

When you want to make a line chart easier to read by adding horizontal and vertical lines.
When you create a bar chart and want to show exact value levels behind the bars.
When you want to highlight specific intervals on the x or y axis for better data interpretation.
When you want to customize the look of your chart by changing grid line style or color.
Syntax
Matplotlib
ax.grid(b=True, which='major', axis='both', color='gray', linestyle='--', linewidth=0.5)

b turns grid lines on or off (True or False).

which controls if grid lines are for 'major', 'minor', or 'both' ticks.

Examples
Turns on the default grid lines for both axes.
Matplotlib
ax.grid(True)
Shows only minor grid lines on the y-axis with dotted lines.
Matplotlib
ax.grid(b=True, which='minor', axis='y', linestyle=':')
Shows grid lines in red color with thicker width.
Matplotlib
ax.grid(b=True, color='red', linewidth=1.5)
Sample Program

This code creates a simple line chart with points. It adds grid lines that are dashed and gray to help see the values better.

Matplotlib
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()
ax.plot(x, y, marker='o')

# Turn on grid lines with dashed style and gray color
ax.grid(True, linestyle='--', color='gray', linewidth=0.7)

plt.show()
OutputSuccess
Important Notes

You can control grid lines separately for x-axis, y-axis, or both using the axis parameter.

Minor grid lines appear between major ticks and can be enabled by setting which='minor' and enabling minor ticks.

Changing grid line style and color helps make your chart clearer or match your design.

Summary

Grid lines improve chart readability by showing reference lines behind data.

You can customize grid lines by turning them on/off, choosing axis, style, color, and width.

Use grid lines to make your charts easier to understand at a glance.