Debug School

rakesh kumar
rakesh kumar

Posted on

How to draw grid and customize grid over plot area in Matplotlib

grids refer to the set of horizontal and vertical lines over the plot area. Gridlines are useful for a better understanding of the data on the plots. Typically, these lines are aligned with the major tick marks on both the x-axis and the y-axis. They can enhance the readability of the plot and make it easier to estimate values.

Image description

Basic Plot with Grids

ax.grid(True)
Enter fullscreen mode Exit fullscreen mode
import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

# create a plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.plot(x, y)

# Add grid
ax.grid(True)

# set the title
ax.set_title('Basic Plot with Grids')

# Show the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Image description

Customizing Grid

Customizing gridlines includes linestyle, linewidth, color, and transparency.

ax.grid(True, linestyle='-.', linewidth=1, color='red', alpha=0.9)
Enter fullscreen mode Exit fullscreen mode

Example
This example demonstrates how to customize the gridline by changing its linestyle, linewidth, color, and transparency.

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Customize grid
ax.grid(True, linestyle='-.', linewidth=1, color='red', alpha=0.9)

# set the title
ax.set_title('Customizing Grids')

# Show the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Adding Minor Gridlines

In addition to major gridlines, Matplotlib supports the inclusion of minor gridlines. These are the lines positioned between the major gridlines and aligning with the minor tick marks on both the x-axis and the y-axis. You can use the pyplot.minorticks_on() and plt.grid(which='minor') to add gridlines corresponding to the minor ticks.
Example
This example demonstrates how to add both the major and minor gridlines to a plot.

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Add major grid
ax.grid(True)

# Add minor grid
ax.minorticks_on()
ax.grid(which='minor', linestyle=':', linewidth=0.5, color='red', alpha=0.5)

# set the title
ax.set_title('Major and Minor Gridlines')

# Show the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output

Image description

On executing the above code we will get the following output −

Manually adding the grids
This approach involves explicitly specifying the positions of vertical and horizontal lines. By iterating through specific intervals or values, users can draw gridlines at desired locations. This involves using functions like pyplot.axvline() and pyplot.axhline() to draw vertical and horizontal lines, respectively.

for pt in np.arange(0, 1.01, 0.3):
   plt.axvline(pt, lw=0.5, color='black', alpha=0.5)
Enter fullscreen mode Exit fullscreen mode

Example
Here is an example that manually draws vertical grid lines at every third point on the x-axis.

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Set x and y tick locations
plt.xticks(np.arange(0, 1.01, 0.1))
plt.yticks(np.arange(0, 1.01, 0.1))
plt.title('Manually Drawing the Grids ')

# Draw grid lines for every third point on the x-axis
for pt in np.arange(0, 1.01, 0.3):
   plt.axvline(pt, lw=0.5, color='black', alpha=0.5)

# Show the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output
On executing the above code we will get the following output −

Image description

Hiding the gridlines
Hiding or removing the gridlines in a plot can be achieved by specifying the boolean value False to the grid() function.

Example
Here is an example that hide gridlines and axes (X and Y axis) of a plot.

import numpy as np
import matplotlib.pyplot as plt

#  Create a figure
fig = plt.figure(figsize=(7, 4))

# Generate data
x = np.linspace(-10, 10, 50)
y = np.sin(x)

# Plot horizontal line
plt.axhline(y=0, c="green", linestyle="dashdot", label="y=0")

# Plot sine curve
plt.plot(x, y, c="red", lw=5, linestyle="dashdot", label="y=sin(x)")

# Hide gridlines
plt.grid(False)

# Hide axes
plt.axis('off')

# Add legend
plt.legend()

# Show plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output
On executing the above code you will get the following output −

Image description

Gridlines Across The Subplots
When comparing data across multiple subplots, it's useful to have gridlines across all subplots to maintain visual comparisons between plots.

Example
Here is an example that demonstrates how to plot grids across subplots.

import matplotlib.pyplot as plt

# Data
d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
f = [0, 1, 0, 0, 1, 0, 1, 1, 0]

# Create figure and subplots
fig = plt.figure(figsize=(7,4))
fig.set_size_inches(30, 10)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Plot data on subplots
ax1.plot(d, marker='.', color='b', label="1 row")

# Draw grid lines behind bar graph
ax2.bar(range(len(d)), d, color='red', alpha=0.5)

# Enable grids on both subplots
ax1.grid()
ax2.grid()

# Display the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output
On executing the above code you will get the following output −

Image description

Top comments (0)