لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

# Python Data Science Matplotlib Adding Grid Lines to Plot Or Graph

With Pyplot you can Add Grid Lines to a Plot: Use the grid() function to add grid lines to the plot.

Example 1: Add grid lines to the plot.

Code

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([245, 255, 265, 275, 285, 295, 305, 315, 325, 335])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)
plt.grid()

plt.show()

the output will be

Specifying Which Grid Lines Should Be Displayed

The axis parameter can be used in the grid() function to specify which grid lines to display.

Legal values are: 'x', 'y'. Default value is 'both'.

Example 2: Display only grid lines for the x-axis.

Code

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([245, 255, 265, 275, 285, 295, 305, 315, 325, 335])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)
plt.grid(axis = 'x')
plt.show()

the output will be

Example 3: Display only grid lines for the y-axis.

Code

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([245, 255, 265, 275, 285, 295, 305, 315, 325, 335])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)
plt.grid(axis = 'y')
plt.show()

the output will be

Setting Line Properties for the Grid

The line properties of the grid can also be specified in the following manner.
grid(color = 'color', linestyle = 'linestyle', linewidth = number).

Example 4: Display only grid lines for the y-axis

Code

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)
plt.show()

the output will be