What is matplotlib.bar() in python?
Matplotlib provides a multitude of functions to visualize and plot data. Bar charts are a common way to represent data graphically in the form of adjacent bars. The bars can be plotted horizontally or vertically. One axis represents the data measurement, while the other represents the frequency that corresponds to that data.
The matplotlib.bar() function plots a bar graph to make comparisons between discrete values.
Syntax
plt.bar(x, height, width, bottom, align)
Parameters
x: A sequence or scalar that represents the x-coordinates of the bars.height: A sequence or scalar that represents the heights of the bars.width: A sequence or scalar that represents the width of the bars. The default is 0.8. (Optional)bottom: A sequence or scalar that represents the y-coordinates of the bars. (Optional)align: The options arecenteroredge. The default iscenter. (Optional)
Return value
matplotlib.bar() returns a container object with bars.
Code
#import librariesimport numpy as npimport matplotlib.pyplot as plt#initialize dictionarydic = {'A':20, 'B+':15, 'B':15, 'C':25,'D':10, 'F':5}#make seperate lists for grades and number of studentsgrades = list(dic.keys())no_of_students = list(dic.values())#set figure sizechart = plt.figure(figsize = (10, 5))#plot the barsplt.bar(grades, no_of_students, color ='maroon',width = 0.4)#set labelsplt.xlabel("Grades")plt.ylabel("Number of students")plt.title("Student Grades")plt.show()
Explanation
The function plots a bar chart that displays grades and the total number of students who got these respective grades. The bar width is set to 0.4, and the color is set to maroon, as shown in the code.