Create major and minor gridlines with different linestyles in Matplotlib Python
Grid lines, which cover the whole chart and indicate the axis divisions, are horizontal and vertical lines. They aid chart viewers in figuring out what value an unlabeled data point represents. Grid lines give the viewer crucial cues, particularly for large or complex charts.
In this article, we will learn how to create different line styles for major and minor gridlines.
How to Customize the different line styles of the Gridlines
An open-source library program called Matplotlib allows you to make excellent data visualization graphical plots in Python. Different plot types, including scatterplots, histograms, error charts, box plots, and more, are available in Matplotlib. Additionally, it contains an extension for the numpy library.
Using the Matplotlib Python package, you will begin creating a plot in this part. The data points come from trigonometric procedures using cos.
Step 1: Importing the necessary library
from matplotlib import pyplot as plt import numpy as np
Step 2: Define theĀ cosplot()
function to create value points.
def cosplot(): fig, ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 4): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax
Step 3: Call the function cosplot()
and plot the graph.
ax = cosplot() plt.show()
The output will be:
Step 4: Add major and minor gridlines
The different line style options which you can use are:
'-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
ax.grid(which='major', color='black', linewidth=0.8) ax.grid(which='minor', color='red', linestyle=':', linewidth=0.7) ax.minorticks_on() plt.show()
The “which” option in the aforementioned command has three possible values: major, minor, and both. These values indicate the Matplotlib gird lines that should be shown. To display the minor grid on the chart, “ax.minorticks_on()” is also required.
So the final code will be:
from matplotlib import pyplot as plt import numpy as np def cosplot(): fig, ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 4): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = cosplot() ax.grid(which='major', color='black', linewidth=0.8) ax.grid(which='minor', color='red', linestyle=':', linewidth=0.7) ax.minorticks_on() plt.show()
The output will be:
The matplolib library’s color and line style options let you alter the grid line’s appearance. You can choose as per your wish and create different linetyle for a particular graph.
Leave a Reply