Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Pandas
  • Numpy
  • Seaborn
  • Ploty
  • Data visualization
  • Data Analysis
  • Power BI
  • Tableau
  • Machine Learning
  • Deep Learning
  • NLP
  • Computer Vision
  • Data Science for Beginners
  • Data Science interview questions
  • Data analysis interview questions
  • NLP Interview questions
Open In App
Next Article:
Grids in Matplotlib
Next article icon

Grids in Matplotlib

Last Updated : 15 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Grids are made up of intersecting straight (vertical, horizontal, and angular) or curved lines used to structure our content. Matplotlib helps us to draw plain graphs but it is sometimes necessary to use grids for better understanding and get a reference for our data points. Thus, Matplotlib provides a grid() for easy creation of gridlines with tonnes of customization.

matplotlib.pyplot.grid()

grid() function in the Pyplot module of the Matplotlib library is used to configure the grid lines in a plot.

Syntax:

matplotlib.pyplot.grid(True, color = "grey", linewidth = "1.4",  axis = ''Y", linestyle = "-.") 

Parameters:

  • True/False: Specifies whether the grid should be displayed.
  • color: Defines the color of the grid lines.
  • linewidth: Sets the thickness of the grid lines.
  • axis: Determines which axis to apply the grid ("x", "y", or both).
  • linestyle: Specifies the style of the grid lines (e.g., dashed, dotted, etc.).

Returns: It does not return anything; it modifies the existing plot by adding a grid.

Adding Grid Lines to a Plot

grid() function allows us to enable or disable grid lines in a plot. We can also choose to display major grid lines, minor grid lines, or both. Additionally, we can customize the color, linewidth and linestyle of the grid lines to enhance visualization.

Python
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np  # dummy data x1 = np.linspace(0.0, 5.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)  # creates two subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (12, 5))  # Plot without grid ax1.plot(x1, y1) ax1.set_title('Plot without grid')  # plot with grid ax2.plot(x1, y1) ax2.set_title("Plot with grid")  # draw gridlines ax2.grid(True)  plt.show() 

OutputPlot 1

Explanation: We generate dummy data using NumPy, where x1 has evenly spaced values from 0 to 5 and y1 follows cos(2πx) * e^(-x), combining oscillation with exponential decay. Two side-by-side subplots are created ax1 shows the plot without grid lines, while ax2 enables grid lines using ax2.grid(True).

Customizing grid line properties

We can enhance the appearance of grid lines using parameters like color, linestyle, and linewidth.

Python
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np  # dummy data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2)  # set graph color plt.plot(x, y, 'green')  # to set title plt.title("Plot with linewidth and linestyle")  # draws gridlines of grey color using given # linewidth and linestyle plt.grid(True, color = "grey", linewidth = "1.4", linestyle = "-.")  plt.show() 

Output

Explanation: We generate dummy data using NumPy, where x has evenly spaced values from 0 to 2𝜋 and y follows sin(x2) follow he plot is drawn in green, with a title set using plt.title(). Grid lines are enabled using plt.grid(True), customized with grey color, linewidth of 1.4 and a dash-dot linestyle.

Displaying grid lines for a specific axis

Matplotlib allows us to display gridlines only for the x-axis or y-axis.

1. Display only grid lines for the x-axis

Use axis='x' to enable grid lines only along the x-axis.

Python
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np  # dummy data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2)  # set graph color plt.plot(x, y, 'green')  # to set title plt.title("Plot with linewidth and linestyle")  # draws gridlines of grey color using given # linewidth and linestyle plt.grid(True, color = "grey", linewidth = "1.4",axis = 'x')  plt.show() 

Output

Explanation: Grid lines are enabled only along the x-axis using plt.grid(True, axis='x'), customized with grey color and a linewidth of 1.4.

2. Display only grid lines for the y-axis

Use axis='y' to enable grid lines only along the y-axis.

Python
# Implementation of matplotlib function import matplotlib.pyplot as plt import numpy as np  # dummy data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2)  # set graph color plt.plot(x, y, 'green')  # to set title plt.title("Plot with linewidth and linestyle")  # draws gridlines of grey color using given # linewidth and linestyle plt.grid(True, color = "grey", linewidth = "1.4",  axis = 'y')  plt.show() 

Output

Explanation: Grid lines are enabled only along the y-axis using plt.grid(True, axis='y'), customized with grey color and a linewidth of 1.4.


Next Article
Grids in Matplotlib

N

nishkarsh146
Improve
Article Tags :
  • Python
  • Python-matplotlib
Practice Tags :
  • python

Similar Reads

    Matplotlib.pyplot.grid() in Python
    matplotlib.pyplot.grid() function in Matplotlib is used to toggle the visibility of grid lines in a plot. Grid lines help improve readability of a plot by adding reference lines at major and/or minor tick positions along the axes. Example:Pythonimport matplotlib.pyplot as plt fig, ax = plt.subplots(
    3 min read
    Matplotlib.axes.Axes.grid() in Python
    Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
    2 min read
    Introduction to Matplotlib
    Matplotlib is a powerful and versatile open-source plotting library for Python, designed to help users visualize data in a variety of formats. Developed by John D. Hunter in 2003, it enables users to graphically represent data, facilitating easier analysis and understanding. If you want to convert y
    4 min read
    Matplotlib - Axes Class
    Matplotlib is one of the Python packages which is used for data visualization. You can use the NumPy library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is used for making 2D plots from data in arrays. Axes class Axes is the most basic and flexible
    4 min read
    Line chart in Matplotlib - Python
    Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of Matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. In this article, we will learn about lin
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences