Easy Tutorial
❮ Home Matplotlib Bar ❯

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:

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:

❮ Home Matplotlib Bar ❯