Matplotlib Grid Lines
We can use the grid()
method from pyplot to set the grid lines in the chart.
The syntax for the grid()
method is as follows:
matplotlib.pyplot.grid(b=None, which='major', axis='both', )
Parameter Description:
b: Optional, defaults to None. Can set a boolean value, true to show grid lines, false to hide them. If **kwargs parameters are set, the value is true.
which: Optional, possible values are 'major', 'minor', and 'both', default is 'major', indicating the grid lines to which changes are applied.
axis: Optional, sets which direction's grid lines to display, can be 'both' (default), 'x', or 'y', representing both directions, x-axis direction, or y-axis direction respectively.
**kwargs: Optional, sets the grid style, which can be color='r', linestyle='-', and linewidth=2, representing the color, style, and width of the grid lines respectively.
The following example adds a simple grid line using default 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("tutorialpro 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, setting the axis parameter to 'x', to display grid lines in the x-axis direction:
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("tutorialpro grid() Test")
plt.xlabel("x - label")
plt.ylabel("y - label")
plt.plot(x, y)
plt.grid(axis='x') # Set to display grid lines in the x-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, with the format as follows:
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 width of the line, 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("tutorialpro 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: