Sunday 24 September 2023

How to Add Gridlines to a Matplotlib Plot?

 

Gridlines are horizontal and vertical lines that extend across the plot area, used to visualize the data points against the actual plot. We can add gridlines to a plot using grid() method.

 

Example

plt.grid()

 

Following table summarizes the parameters of grid method.

 

Parameter

Description

which

Following values are accepted for this argument.

a. 'major': Show gridlines for major ticks only.

b. 'minor': Show gridlines for minor ticks only.

c. 'both' (default): Show gridlines for both major and minor ticks.

axis

Specifes which accees to apply the gridlines to. Following are the possible values.

 

a. 'both' (default): Show gridlines on both the x-axis and y-axis.

b. 'x': Show gridlines only on the x-axis.

c. 'y': Show gridlines only on the y-axis.

 

add_grid_lines.py

import matplotlib.pyplot as plt

# Sample data
year = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
population = [1246.2, 1262.6, 1279.7, 1297.4, 1315.8, 1334.9, 1354.7, 1374.2, 1407.6, 1417.2]

# Create a line plot
plt.plot(year, population)

# Add grid lines
plt.grid()

# Add labels and title
plt.xlabel('Year')
plt.ylabel('Population in Millions')
plt.title('India Population in millions by year wise', verticalalignment='center',
          horizontalalignment='center',  color='blue', fontweight='bold',
          backgroundcolor='lightblue')

# Display the plot
plt.show()

 

Output



 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment