💡 Grid lines are horizontal and vertical lines that span the chart to represent axis divisions. They assist chart readers in determining what value is represented by an unlabeled data point. Grid lines provide essential indications to the observer, especially for big or sophisticated charts.
In this article, you will learn how to customize the gridlines by location, style, and width using Python Matplotlib. I’ll show you that with a few lines of Python code you can create awesome gridlines on the graph.
Keep reading to learn more!
What is Matplotlib?
Matplotlib is an open-source library tool to create high-quality data visualization graphical plots in python. It was created and programmed by John D. Hunter in Python in 2003. Matplotlib provides different types of plots such as scatterplots, histograms, errorcharts, box plots, and more. Also, it has a numpy library as an extension. The latest Matplotlib release is version 3.5.2.
Matplotlib has the following features :
- The interactive plots can zoom, pan, and update.
- You can customize the plot’s visual style and layout.
- The plots can be exported into other file formats like PNG, PDF, and SVG.
- You can use third-party libraries such as
holoviews
,hvplot
,gif
,xmovie
, etc., within thismatplotlib
library.
🌎 Learn More: The Ultimate Guide to Matplotlib (Video Course Free)
Initial Stage
In this section, you will start building a plot using the Matplotlib Python library. The data points are derived from cos Trigonometric operations.
Install the matplotlib library in your terminal with the following command:
pip install matplotlib
Now create a new file and start writing the code.
Import the matplotlib and numpy library as shown below: from matplotlib import pyplot as plt import numpy as np
After importing the library, create a cosplot
function to plot the graph.
Define the cosplot()
function to create value points for the plot with below lines of code:
def cosplot(): fig, ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax
The numpy linspace()
makes the plotting lines spaced evenly distributed within the specified interval.
You can see the interval is between 0 to 10 on the x-axis. There are eight lines on the graph (see Graph 1) drawn with the range function.
The value point for a plot is based on the command ax.plot(x, np.cos(x + i * .5) * (10 - i))
. Finally, the function returns the subplot.
Calling the function cosplot()
as below will dispay the plot (See Graph 1).
ax = cosplot() plt.show()
Display Major and Minor Grid
This section will show you how to display the Major and Minor Grid lines using Matplotlib on the graph.
Now let’s see how to display the major grid on the graph.
With a single line of Python code,
ax.grid(True)
The major grid is shown on the graph. (See Graph 2)
The grid(True)
command by default, the only major grid is shown. But how to get a minor grid on the the chart? ❓ Continue Reading!
The following python lines of code will display both the major and minor grid lines on the chart.
ax.grid(which='major', color='#DDDDDD', linewidth=0.8) ax.grid(which='minor', color='#EEEEEE', linestyle=':', linewidth=0.5) ax.minorticks_on()
The argument in the above command, “which,” has three values, major, minor, and both, that specify the Matplotlib on which gird lines to display. You must also include the command “ax.minorticks_on()” to show the minor grid on the chart.
See below Graph3, where both gridlines are displayed.
Customize Grid Location
This section is the main topic of this post, where you will see how to set the location of the minor grid using the Python matplotlib library.
You can change the location of the minor grid using matplotlib.ticker.AutoMinorLocator()
library.
Import the autominorlocator
library as per below command:
from matplotlib.ticker import AutoMinorLocator
Fix the position of the minor grid from the following command
minor_locator = AutoMinorLocator(4) ax.xaxis.set_minor_locator(minor_locator) ax.yaxis.set_minor_locator(minor_locator)
The AutoMinorLocator
is set to 4, placing 3 minor ticks equally between each pair of major ticks. Next, you fix the position of grid lines using the set_minor_locator
function for the x and y-axis as per the above commands.
Once you have executed the following commands
from matplotlib import pyplot as plt from matplotlib.ticker import AutoMinorLocator import numpy as np def sinplot(): fig,ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = sinplot() minor_locator = AutoMinorLocator(4) ax.xaxis.set_minor_locator(minor_locator) ax.yaxis.set_minor_locator(minor_locator) ax.grid(which='minor', color='black', linestyle=':', linewidth=0.5) ax.minorticks_on() plt.show()
The window will pop up below where you can find in Graph 4 that the position of Minor gridlines is set between major ticks.
Now let’s see how to set the position for the major grid line using matplotlib.ticker.FixedLocator
class.
The following command will inform matplotlib about the position of the major grid.
from matplotlib import pyplot as plt from matplotlib.ticker import AutoMinorLocator, FixedLocator import numpy as np def sinplot(): fig,ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = sinplot() ax.grid(which='major', color='blue', linewidth=0.8) minor_locator = AutoMinorLocator(2) major_locator =FixedLocator([2,4,6,8,10]) ax.xaxis.set_minor_locator(minor_locator) ax.yaxis.set_minor_locator(minor_locator) ax.xaxis.set_major_locator(major_locator) ax.grid(which='minor', color='red', linestyle=':', linewidth=0.5) plt.show()
Here we have fixed the position for the major grid using FixedLocator
class with 2,4,6,8,10 points on the x-axis (Refer to Code which is highlighted).
Execute the above code, and you get the below graph 5. The major grid lines are blue in color and set at 2,4,6,8,10 points on the x-axis. See Graph 5.
Customize Grid Style
You can customize the design of the grid line using the color
and linestyle
parameters in the matplolib library.
Let’s see how it works.
Execute the below command to change the style for the major gridline:
from matplotlib import pyplot as plt import numpy as np def sinplot(): fig,ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = sinplot() ax.grid(which='major', color='blue',linestyle='dotted') ax.minorticks_on() plt.show()
The color of the grid line is set to blue, and linestyle is set to 'dotted'
or ':'
style (refer to the code which is bolded).
Run the above command, and the output will be generated as follows. See Graph 6.
The line style has three other values or line styles you can choose.
linestyle= "solid" ______________
linestyle= "dashed" —----------------
linestyle = "dashdot" -.-.-.-.-.-.-.-.
Also, you can change the minor grid style by adding “minor” to which parameter in the same way.
ax.grid(which='minor', color='blue',linestyle='dotted')
Customize Grid Width
Do you want to increase the thickness of the grid lines in your plot?
Yes, you can do it with the linewidth
parameter.
Execute the below command:
from matplotlib import pyplot as plt import numpy as np def sinplot(): fig,ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = sinplot() ax.grid(which='major', color='blue', linewidth=1,linestyle='dotted’) ax.minorticks_on()
The following output is displayed.
Mimic Ggplot2 with matplolib
This last and most exciting section will teach you how to design a graph similar to Ggplot2.
Ggplot2 is the r package for plotting attractive graphical charts. This plot has the design of grey background with a white major gridline (See Graph 8).
Run the below command to get the Ggplot2 style.
from matplotlib import pyplot as plt from matplotlib.ticker import AutoMinorLocator import numpy as np def sinplot(): fig,ax = plt.subplots() x = np.linspace(0, 10, 100) for i in range(1, 9): ax.plot(x, np.cos(x + i * .5) * (10 - i)) return ax ax = sinplot() ax.set_facecolor('#EBEBEB') ax.grid(which='major', color='white', linewidth=1.2) ax.grid(which='minor', color='white', linewidth=0.6) ax.tick_params(which='minor', bottom=False, left=False) ax.minorticks_on() ax.xaxis.set_minor_locator(AutoMinorLocator(2)) ax.yaxis.set_minor_locator(AutoMinorLocator(2)) plt.show()
set_facecolor('#EBEBEB')
will set the grey color in the background. Then set the color and line width of major and minor grid lines as bold above.
With AutoMinorLocator(2)
function shows only 1 minor grid between major gridlines that mimics the Ggplot2 style.
See Graph 8 below:
Conclusion
Gridlines allow graph readers to grasp the value from the chart without it easily. With a few lines of Python, you can customize the style of grid lines.
Also, with one line of code, you can change the width and location of gridlines.
Finally, this blog post helped you create a fantastic gglot2 graph using python matplotlib.
Try it out and enjoy designing grid lines.