Bar charts are used to present categorical data with rectangular bars. The bars can be plotted vertically or horizontally, and their heights/lengths are proportional to the values that they represent.
Matplotlib is the library used for 2D plots of arrays in Python.
To plot the bar chart, import the Matplotlib library first. The command used to do this is:
import matplotlib.pyplot as plt
The command to plot a bar chart is:
plt.bar(x, height, width=0.8, bottom=None, *, align='center')
center
or edge
. These values define whether the bars will center their base on the x-coordinate, or align their left edge with the x-coordinate.A container with all the bars and optional errorbars.
The following code shows how to plot a basic vertical bar chart:
import matplotlib.pyplot as plt# Pass the x and y cordinates of the bars to the# function. The label argument gives a label to the data.plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Data 1")plt.legend()# The following commands add labels to our figure.plt.xlabel('X values')plt.ylabel('Height')plt.title('Vertical Bar chart')plt.show()
The following code shows how to plot a basic horizontal bar chart. Use plt.barh
instead of plt.bar
.
import matplotlib.pyplot as plt# Pass the x and y cordinates of the bars to the# function. The label argument gives a label to the data.plt.barh(["Cats","Dogs","Goldfish","Snakes","Turtles"],[5,2,7,8,2], align='center', label="Data 1")plt.legend()plt.ylabel('Pets')plt.xlabel('Popularity')plt.title('Popularity of pets in the neighbourhood')plt.show()
We can also plot bar charts by comparing two data series side by side; this allows us to observe their differences more easily. The code below shows how to do this:
import numpy as npimport matplotlib.pyplot as plt# data to plotmarks_john = [90, 55, 40, 65]marks_sam = [85, 62, 54, 20]# create plotfig, ax = plt.subplots()bar_width = 0.35X = np.arange(4)p1 = plt.bar(X, marks_john, bar_width, color='b',label='John')# The bar of second plot starts where the first bar endsp2 = plt.bar(X + bar_width, marks_sam, bar_width,color='g',label='Sam')plt.xlabel('Subject')plt.ylabel('Scores')plt.title('Scores in each subject')plt.xticks(X + (bar_width/2) , ("English", "Science","Sports", "History"))plt.legend()plt.tight_layout()plt.show()
Free Resources