In this article, we will learn how to plot a Bar Chart in Python using Matplotlib library. In our earlier articles, we learnt how to plot a Histogram and line plots. So this is going to be a follow up on that. But this time with Bar Charts!
So are you ready to learn about it? Great! Then let us start right away!
Plot Bar Chart In Python Using Matplotlib – The Basics
So to begin with, we will start with the basics. Alright? Because if we get our basics right, everything else will become very clear. I hope you agree with me! So here is the first basic thing to know about:
What Is A Bar Chart?
A bar chart is a chart that uses rectangular bars whose length is equal to the value it represents. Now this bar can either be a vertical bar or a horizontal bar. Alright? So it can be used in either ways. But the main thing is that it’s width is the value that it represents!
So it is quite simple then. Right? But how are we going to plot a bar chart using Python? Any Guess? Yep, using our good old Matplotlib library!
So how does the code of a simple bar chart using Matplotlib look like? Let us take a look at it next!
Example Plot Of A Bar Chart In Python Using Matplotlib
So here is our example code that shows us how we can do this:
import matplotlib.pyplot as plt plt.bar([10, 12, 15], [18, 6, 24]) plt.show()
Okay. It looks pretty straight forward. So what is going on here?
As you can see in the first line, we are importing the standard plt module from the Matplotlib library. Now this module is like the Swiss army knife of the library. Because this is the module that has all the plotting functions.
So in this case, since we need to plot a bar chart, we will call the bar( ) function! Alright? So that is what we did in line 2.
plt.bar([10, 12, 15], [18, 6, 24])
But what are those two list values we are passing here? They are the X & Y co-ordinates. So the first list [10, 12, 15] gives the x-axis co-ordinate values. It is where the left margin of our bars will be drawn. On the other hand, the second list [18, 6, 24] gives us the height of the bars!
And finally in line3, we call the plt.show( ) function that will display our bar chart!
So how does our final Bar Chart look like? Well, take a look at it for yourself!
So there you go! That is how we plot a bar chart in Python using Matplotlib. It is quite easy to plot. Right? But if you still have any doubts, do let me know in the comments below. I will be more than happy to help! 🙂