Matplotlib Grid Lines
We can use the grid() method in pyplot to set the grid lines in a chart.
The syntax of the grid() method is as follows:
matplotlib.pyplot.grid(b=None, which='major', axis='both', )
Parameter Description:
- b: Optional, defaults to None, can be set to a boolean value; true shows grid lines, false hides them; if **kwargs parameters are set, the value is true.
- which: Optional, possible values are 'major', 'minor', and 'both', defaulting to 'major', which indicates the grid lines to which the changes apply.
- axis: Optional, sets which direction of grid lines to display; can be 'both' (default), 'x', or 'y', indicating both directions, the x-axis direction, or the y-axis direction, respectively.
- **kwargs: Optional, sets the grid style; can be color='r', linestyle='-', and linewidth=2, indicating the color, style, and width of the grid lines, respectively.
The following example adds a simple grid line using the default parameter values:
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
x
=
np.
array
(
[
1
,
2
,
3
,
4
]
)
y
=
np.
array
(
[
1
,
4
,
9
,
16
]
)
plt.
title
(
"RUNOOB grid() Test"
)
plt.
xlabel
(
"x - label"
)
plt.
ylabel
(
"y - label"
)
plt.
plot
(
x
,
y
)
plt.
grid
(
)
plt.
show
(
)
The display result is as follows:

The following example adds a simple grid line with the axis parameter set to x, showing grid lines along the x-axis:
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
x
=
np.
array
(
[
1
,
2
,
3
,
4
]
)
y
=
np.
array
(
[
1
,
4
,
9
,
16
]
)
plt.
title
(
"RUNOOB grid() Test"
)
plt.
xlabel
(
"x - label"
)
plt.
ylabel
(
"y - label"
)
plt.
plot
(
x
,
y
)
plt.
grid
(
axis
=
'x'
)
Set y to show grid lines along that axis direction
plt.
show
(
)
The display result is as follows:

The following example adds a simple grid line and sets the style of the grid lines, in the following format:
grid(color = 'color', linestyle = 'linestyle', linewidth = number)
Parameter Description:
color:'b' blue, 'm' magenta, 'g' green, 'y' yellow, 'r' red, 'k' black, 'w' white, 'c' cyan, '#008000' RGB color string.
linestyle:'‐' solid line, '‐‐' dashed line, '‐.' dash-dot line, ':' dotted line.
linewidth: Sets the line width; can be set to a number.
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
x
=
np.
array
(
[
1
,
2
,
3
,
4
]
)
y
=
np.
array
(
[
1
,
4
,
9
,
16
]
)
plt.
title
(
"RUNOOB grid() Test"
)
plt.
xlabel
(
"x - label"
)
plt.
ylabel
(
"y - label"
)
plt.
plot
(
x
,
y
)
plt.
grid
(
color
=
'r'
,
linestyle
=
'--'
,
linewidth
=
0.5
)
plt.
show
(
)
The display result is as follows:
