SecondlyMatplotlib gridlines make charts look more interactive and self-explanatory. This Matplotlib gridlines supports multiple attributes like which( major, minor), color, line style, etc. This article will give you an overview of Matplotlib gridlines with step by step Examples.
Matplotlib gridlines: step by step –
Step 1:
Firstly, Create a simple line chart with Matplotlib. Here we are not adding gridlines.
import matplotlib.pyplot as plt
x_axis= [100,150,200]
y_axis = [50,21,37]
plt.plot(x_axis, y_axis)
plt.title('Demo chart')
plt.show()
The above code will draw the below line chart with no gridlines.

Step 2:
Secondly, Here we will add Matplotlib gridlines in the above chart. You may refer to the below syntax example.
plt.grid(b=True, which='major', color='#445577', linestyle=':')
Let’s integrate this gridline code in the above example.
import matplotlib.pyplot as plt
x_axis= [100,150,200]
y_axis = [50,21,37]
plt.plot(x_axis, y_axis)
plt.title('Demo chart')
plt.grid(b=True, which='major', color='#445577', linestyle=':')
plt.show()
Bonus Tips for Matplotlib gridlines :
1. How to add major and Minor Gridlines –
It is quite similar to step 2 example. But we need to add two extra lines here.
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#900000', linestyle=':')
Here is the complete code for adding major and Minor Gridlines.
import matplotlib.pyplot as plt
x_axis= [100,150,200]
y_axis = [50,21,37]
plt.plot(x_axis, y_axis)
plt.title('Demo chart')
plt.grid(b=True, which='major', color='#300000', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#900000', linestyle=':')
plt.show()
See the output.

2. How to Define the linewidth in the gridlines?
In order to define the linewidth with the graph. You need to add a simple parameter linewidth in the grid function.
plt.grid(b=True, which='major', color='#300000', linewidth='0.9', linestyle='-')
You may add this parameter in a minor grid as well. Well, I think giving full code at a place helps more than reading a thousand words. So here is the full code for this with its output.
import matplotlib.pyplot as plt
x_axis= [100,150,200]
y_axis = [50,21,37]
plt.plot(x_axis, y_axis)
plt.title('Demo chart')
plt.grid(b=True, which='major', color='#300000', linewidth='0.9', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#900000',linewidth='0.3', linestyle=':')
plt.show()

As you can see that we have defined the linewidth value more in major gridline. Hence it is more visual than minor gridlines.
Conclusion –
Well, Grid Lines has many attributes. In this tutorial, we tried to cover the basic concept and code flow for gridlines. We have also covered major syntax examples associated with it. Still, If we miss something which you guys think important to cover in this topic. Please comment on that.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.