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

  1. x: A sequence or scalar that represents the x-coordinates of the bars.
  2. height: A sequence or scalar that represents the heights of the bars.
  3. width: A sequence or scalar that represents the width of the bars. The default is 0.8. (Optional)
  4. bottom: A sequence or scalar that represents the y-coordinates of the bars. (Optional)
  5. align: The options are center or edge. The default is center. (Optional)

Return value

matplotlib.bar() returns a container object with bars.

Code

#import libraries
import numpy as np
import matplotlib.pyplot as plt
#initialize dictionary
dic = {'A':20, 'B+':15, 'B':15, 'C':25,
'D':10, 'F':5}
#make seperate lists for grades and number of students
grades = list(dic.keys())
no_of_students = list(dic.values())
#set figure size
chart = plt.figure(figsize = (10, 5))
#plot the bars
plt.bar(grades, no_of_students, color ='maroon',
width = 0.4)
#set labels
plt.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.

Free Resources