Matplotlib Grid
# Matplotlib Grid Lines
# Matplotlib Grid Lines
We can use the grid() method in pyplot to set grid lines in the chart.
The grid() method syntax is as follows:
matplotlib.pyplot.grid(b=None, which='major', axis='both', )
**Parameter Description:**
* **b**: Optional, default is None, can set a boolean value, true means display grid lines, false means do not display, if **kwargs parameter is set, the value is true.
* **which**: Optional, optional values are 'major', 'minor' and 'both', default is 'major', indicates the grid lines to apply changes to.
* **axis**: Optional, set which direction to display grid lines, can be 'both' (default), 'x' or 'y', representing both directions, x-axis direction or y-axis direction respectively.
* ****kwargs**: Optional, set grid style, can be color='r', linestyle='-' and linewidth=2, representing the grid line's color, style and width respectively.
The following example adds a simple grid line, using 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("TUTORIAL grid() Test")
plt.xlabel("x - label")
plt.ylabel("y - label")
plt.plot(x, y)
plt.grid()
plt.show()
The result is as follows:
!(#)
The following example adds a simple grid line, using axis parameter set 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("TUTORIAL grid() Test")
plt.xlabel("x - label")
plt.ylabel("y - label")
plt.plot(x, y)
plt.grid(axis='x')# Set y to display grid lines in the axis direction
plt.show()
The result is as follows:
!(#)
The following example adds a simple grid line and sets the grid line style, format is 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**: Set the line width, can set 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("TUTORIAL 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 result is as follows:
!(#)
YouTip