Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is matplotlib.bar() in python?

Eman Kashif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring