Matplotlib Bar Plot - bar() Function
In this tutorial, we will cover the bar plot in Matplotlib and how to create it.
The bar plot or bar chart is usually a graph/chart that is mainly used to represent the category of data with rectangular bars with lengths and heights that are proportional to the values which they represent.
-
You can plot these bars either vertically or horizontally.
-
We use the bar plot to mainly show the comparison between discrete categories of data.
-
In the bar plot, One axis of the plot is used to represent the specific categories being compared, while the other axis usually represents the measured values corresponding to those categories.
Matplotlib bar()
Function
The bar()
function is used to create a bar plot that is bounded with a rectangle depending on the given parameters of the function. In the Matplotlib API, this function can be used in the MATLAB style use, as well as object-oriented API.
Matplotlib bar()
Function Syntax
The required syntax to use this function with axes object is as follows:
ax.bar(x, height, width, bottom, align)
The parameters of this function are described as follows:
-
x
This parameter is used to represent a sequence of scalar values that represents the x coordinates of the bars. The align
parameter controls if x is the bar center (default) or left edge
-
height
This parameter is either a scalar or sequence of scalar values representing the height(s) of the bars which makes the y-axis value.
-
width
This parameter is either a scalar or array-like and it is optional. The default value of this parameter is 0.8
-
bottom
This is also a scalar or array-like and it is optional. The default value is None.
-
align
The values of this parameter are {'center', 'edge'}, optional, and the default value of this parameter is 'center'
The bar()
function returns a Matplotlib container object with all bars.
Now it's time to dive into some examples of this concept.
Simple Bar Plot:
Given below is a simple example of the bar plot, which represents the number of books offered by the institute:
import numpy as np
import matplotlib.pyplot as plt
data = {'Computer Networks':20, 'DBMS':15, 'Java':30,'C':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
plt.bar(courses, values, color ='magenta',width = 0.4)
plt.xlabel("Books offered")
plt.ylabel("No. of books provided")
plt.title("Books provided by the institute")
plt.show()
Code Explanation:
Here plt.bar(courses, values, color='magenta')
is basically specifying the bar chart that is to be plotted using "Books offered"(by the college) column as the X-axis, and the "No. of books" as the Y-axis.
The color
attribute is basically used to set the color of the bars(magenta ).
The statement plt.xlabel("Books offered")
and plt.ylabel("books provided by the institute")
are used to label the corresponding axes. The plt.title()
function is used to make a title for the graph. And the plt.show()
function is used to show the graph as the output of the previous commands.
The output shown by the above code will be as follows:
Customizing Bar Plot: Stacked Plot
The Stacked bar plots are used to represent different groups of data on the top of one another. The height of the bar mainly depends upon the resulting height of the combination of the results of the groups. The height goes from the bottom to the value instead of going from zero to value
Now let us create a stacked plot and the code is given below:
import numpy as np
import matplotlib.pyplot as plt
N = 5
group_a = (25, 37, 39, 23, 56)
group_b = (29, 36, 38, 25, 22)
ind = np.arange(N) # the x locations for the groups
width = 0.39
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, group_a, width, color='c')
ax.bar(ind, group_b, width,bottom=group_a, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by two groups')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Group A', 'Group B'])
plt.show()
If you will run this code in your own system, then the output will be as follows:
Time For Live Example!
Let us take a look at the Live example: