Sunday 29 October 2023

Adding Grid Lines to Plots in Matplotlib

Using grid method of Pyplot, we can display grid lines on a plot.

Signature

matplotlib.pyplot.grid(b=None, which='major', axis='both', **kwargs)

 

b: If the parameter b is set to True, then it displays grid lines on the plot. If the parameter b is set to False, then grid lines are hidden. By default it is set to None, and the default state depends on  the current state of the grid.

 

which: Specifies which kind of grid lines the settings should apply. Possible values are major, minor and both.

 

axis: It can take one of three values.

1.   both: Apply grid lines to both the axis

2.   x: Apply grid lines to x-axis

3.   y: Apply grid lines to y-axis

 

Apart from this you can specify the arguments like color, linestyle, alpha parameters (alpha parameter control the transparency or opacity of graphical elements).

 

Example 1: Plot grid lines on both x and y axis.

plt.plot(x, y, label='y = 10 * x + 123')

 

add_grid_lines.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True)
plt.show()

 

Output

 


Example 2: Add only horizontal grid lines.

plt.grid(True, axis='y')

 

add_horizontal_grid_lines_only.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, axis='y')
plt.show()

Output


 

Example 3: Customize grid line style, color, opacity.

plt.grid(True, linestyle='--', color='red', alpha=0.5)

 

customize_grid_line.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, linestyle='--', color='red', alpha=0.5)
plt.show()

 

Output

 


 

Example 4: ‘which’ parameter example.

 

You need to turn on minor tick by executing below line.

plt.minorticks_on()

 

Find the below working application.

 

which_parameter.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 100)
y = 10 * x + 123

plt.plot(x, y)

plt.minorticks_on()

# Customize major gridlines only
plt.grid(True, which='major', linestyle='--', color='red')

# Customize minor gridlines only
plt.grid(True, which='minor', linestyle=':', color='blue')

# Show the plot
plt.show()

Output



 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment