codingstreets
Search
Close this search box.
python-matplotlib-grid-lines

Introduction to Matplotlib Grid Lines

In This Article, You Will Learn About Python Matplotlib Grid Lines.

Python Matplotlib Grid Lines – Before moving ahead, let’s take a look at Python Matplotlib Labels & Title

Table of Contents

Add Grid Lines to a Plot

To add grid lines in graph, we can use grid() function with Pyplot.

Example: Add grid lines to graph.

				
					import matplotlib.pyplot as plt
import numpy as np

x_axis = np.array([10, 18, 25, 36, 48])
y_axis = np.array([20, 26, 17, 31, 29])

plt.title('Record')
plt.xlabel('Data')
plt.ylabel('year')

plt.plot(x_axis, y_axis)

plt.grid()

plt.show()

				
			
python-matplotlib-grid-lines

As shown above, it returned a graph with Grid Lines of both axes.

Mention Which Grid Lines to Display

To specify which grid lines to display, we can pass a parameter axis in grid() function.

Note: Default value is both. Valid values are x, y and both.

Example: Displaying the grid lines only for x-axis.

				
					import matplotlib.pyplot as plt
import numpy as np

x_axis = np.array([10, 18, 25, 36, 48])
y_axis = np.array([20, 26, 17, 31, 29])

plt.title('Record')
plt.xlabel('x')
plt.ylabel('y')

plt.plot(x_axis, y_axis)

plt.grid(axis='x')

plt.show()

				
			
python-matplotlib-grid-lines

As shown above, it returned a graph only with Grid Lines of x-axis.

Example: Displaying the grid lines only for y-axis.

				
					import matplotlib.pyplot as plt
import numpy as np

x_axis = np.array([10, 18, 25, 36, 48])
y_axis = np.array([20, 26, 17, 31, 29])

plt.title('Record')
plt.xlabel('x')
plt.ylabel('y')

plt.plot(x_axis, y_axis)

plt.grid(axis='y')

plt.show()

				
			
python-matplotlib-grid-lines

As a result, it returned Grid Lines only for y-axis.

Line Properties of the Grid

To set the grid line’s properties, we can pass color, linestyle, and linewidth as parameters in the grid() function.

Example: Displaying the grid lines for both axes.

				
					import matplotlib.pyplot as plt
import numpy as np

x_axis = np.array([10, 18, 25, 36, 48])
y_axis = np.array([20, 26, 17, 31, 29])

plt.title('Record')
plt.xlabel('Data')
plt.ylabel('year')

plt.plot(x_axis, y_axis)

plt.grid(color='r', linestyle=':', linewidth=1.2)

plt.show()

				
			
python-matplotlib-grid-lines

As shown above, it returned a graph with Grid Lines for both axes and other properties.

Note: Supported values for Grid Line are ‘-‘, ‘–‘,  ‘-.’,  ‘:’,  ‘None’,  ‘ ‘,  ”,  ‘solid’,  ‘dashed’,  ‘dashdot’,  ‘dotted’.

If you find anything incorrect in the above-discussed topic and have any further questions, please comment below.

Connect on:

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on