How to set a grid graph line in Python

Adding grid lines to the graph plot

First, we have to install two modules:

import matplotlib
import matplotlib.pyplot as plt

Then, we enter the code:

import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 82, 90, 95, 100, 103, 110, 115, 120, 125])
y = np.array([240, 250, 264, 270, 280, 290, 294, 310, 320, 330])
plt.title("Health Chart")
plt.xlabel("Average people")
plt.ylabel("Calorie Consumption")
plt.plot(x, y)
plt.grid()
plt.show()

Specifying which grid lines to display

We can use the "axis" parameter in the grid function to specify which grid lines to display.

Legal values are 'x', 'y', and 'both'. The default value is 'both'.

import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 82, 90, 95, 100, 103, 110, 115, 120, 125])
y = np.array([240, 250, 264, 270, 280, 290, 294, 310, 320, 330])
plt.title("Health Chart")
plt.xlabel("Average people")
plt.ylabel("Calorie Consumption")
plt.plot(x, y)
plt.grid(axis = 'x')
plt.show()

Setting line properties for the grid

import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 82, 90, 95, 100, 103, 110, 115, 120, 125])
y = np.array([240, 250, 264, 270, 280, 290, 294, 310, 320, 330])
plt.title("Health Chart")
plt.xlabel("Average people")
plt.ylabel("Calorie Consumption")
plt.plot(x, y)
plt.grid(color = 'yellow', linestyle = '--', linewidth = 1.5)
plt.show()

The graph shown above is the output.

This is how to plot grid lines in a graph.

Free Resources