Hey Coders, Let's learn all about bar plots in the matplotlib library. A bar plot is the most common type of chart. These plots are useful to show the relationship between numeric and categoric values. A lot of times, we need to draw a fast conclusion based on the given data. At those times, a bar plot can be used to make our task easier.

Bar plots are essential tools for data analysts and data scientists to analyze and gain insights from the data. This blog will look at bar plots available in the matplotlib library.

Matplotlib

Matplotlib is one of the most used Python data visualization packages for 2D array plots. Matplotlib is a NumPy-based multi-platform data visualization framework. Matplotlib has a variety of plots, such as lines, bars, scatter, histograms, etc.

Let's now see different bar plots which we can plot using the matplotlib library.

bottom: The y coordinates of the bottom side of the bars.

align: Alignment of bars to the x coordinates, default: 'center'

Vertical Bar Plot

Vertical bar plots are the most basic and most used bar plots in Python. Let's plot a basic bar plot of students and their scores to understand vertical bar plots better.

Example 1

#Importing the library
import matplotlib.pyplot as plt
# List of students
students = ['A', 'B', 'C', 'D', 'E']
# Marks of students
marks = [90, 79, 77, 69, 53]
plt.bar(students, marks)
plt.xlabel('Students')
plt.ylabel('Marks')
plt.title('Students Vs Marks bar plot')
plt.show()

Output

Explanation

Here, plt.bar() is used to specify that we are plotting a bar plot with students on the x-axis and marks on the y-axis.

Let’s look at another example of a bar plot.

Example 2

# Importing the library
import matplotlib.pyplot as plt
plt.style.use("ggplot")
# List of years
x = ['2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023']
# List of sales of cars each year
y = [10233, 13423, 14243, 14838, 15323, 10939, 11830, 22343, 23232, 24523, 8023]
# Plotting bar plot
plt.bar(x, y, width=0.5, edgecolor = 'black', color='green')
plt.title("Yearwise Sales of Car ")
plt.xlabel("Years")
plt.ylabel("Number of Cars")
# Adding the Legends
plt.legend(["Year Vs Number of cars"])
plt.show()

Output

Explanation

In the above example of vertical bar plots, we plotted the number of cars produced per year using the bar() function of the matplotlib library. We can also add various styles using style.use() method in the matplotlib library.

Horizontal Bar Plot

Horizontal bar plots represent the data horizontally. These are sideways bar plots whose bars are drawn horizontally.

Example

# Importing the library
import matplotlib.pyplot as plt
plt.style.use("ggplot")
# List of countries
y = ['Germany', 'Japan', 'Mexico', 'China', 'India', 'Canada', 'Russia', 'USA', 'Iran']
# Number of increase in crime rates
x = [2304, 530, 8393, 23032, 21302, 3430, 9323, 18232, 1523]
# Ploting horizontal bar plot
plt.barh(y, x, color='red', edgecolor="black")
# Title to the plot
plt.title("Countrywise Increase in crime rates ")
# Adding the Legends
plt.legend(["Number of crimes"])
plt.show()

Output

Explanation

The barh() is used to specify that we are plotting a horizontal bar plot. You can use ggplot style to make the plot look more detailed. Note that the above data is randomly generated.

Multiple Bar Plot

A Multiple bar plot is also called a Grouped bar plot. A multiple-bar plot is similar to a regular bar plot, except that there are multiple bars in each category in multiple-bar plots.

One of the advantages of this plot is that we don't need to create multiple different plots.

Example

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("dark_background")
# Set the height of the bar
Year15 = (11, 15)
Year16 = (8, 10)
x = np.arange(2)
width = 0.3
# Setting the position of the bar on the x-axis
plt.bar(x-width/2, Year15, width, label="Year2020", color="green")
plt.bar(x+width/2, Year16, width, label="Year2021", color="blue")
plt.ylabel('Tons')
plt.title("Rice and Maize Production Comparison")
labels = ('Rice','Maize')
plt.xticks(x, labels)
plt.legend()
plt.show()

Output

Explanation

In the above example of multiple bar plots, we plotted a year-wise comparison of the production of rice and maize using the same bar() function of matplotlib. This method is handy for comparing different entities with the same parameters.

Stacked Bar Plot

A stacked bar plot is a form of bar plot that shows the composition and comparison of different entities. They are called Stacked bar plots because they look like a series of bars that are stacked on top of each other.

Let's now look at an example of a stacked bar plot.

Example

# Importing the library
import matplotlib.pyplot as plt
# Labels for each team
Teams = ['T1', 'T2', 'T3', 'T4', 'T5' ]
men_means = [18, 32, 26, 31, 23]
women_means = [20, 27, 30, 17, 21]
men_std = [3, 4, 6, 2, 5]
women_std = [3, 5, 2, 3, 4]
# The width of the bars:
width = 0.4
# Subplot function to draw multiple plots
fig,ax = plt.subplots()
# Plotting the bar plot
ax.bar(Teams, men_means, width, yerr=men_std, label='Men', color='red')
# Plotting the women's bar above the men’s bar
ax.bar(Teams, women_means, width, yerr=women_std, bottom=men_means, label='Women', color='blue')
# Setting the title
ax.set_ylabel('Scores', color='black')
ax.set_title('Scores by Teams and gender', color='black')
ax.legend()
plt.show()

Output

Frequently Asked Questions

What is the use of matplotlib?

Python's matplotlib library provides a complete tool for building static, animated, and interactive visualizations. Data analysis is made simpler and more effective using Matplotlib's many features, plot styles, and high-quality outcomes.

What is the use of NumPy in matplotlib?

Numpy is compatible with many popular Python packages like matplotlib and seaborn. Furthermore, NumPy provides multidimensional array objects which are used for various mathematical operations.

What is the use of pandas?

Panda is the most often used open-source Python library for data science, data analysis, and machine learning activities. Using Pandas, we can examine large data sets and draw conclusions based on statistical principles. Pandas can organize disorganized data sets, making them readable and useful.

How do you plot a bar plot in Python?

We can plot a bar plot in Python using Python's built-in libraries like matplotlib and seaborn. Using the matplotlib libraries bar() function, we can plot simple bar plots in Python.

Which are the different types of bar plots?

Some of the most used bar plots in Python are simple bar plots, grouped bar plots, stacked bar plots, horizontal bar plots, etc.

Conclusion

This article discusses the matplotlib bar plot in Python along with different types of bar plots in the matplotlib library. These bar plots are a lot useful in our day-to-day life, and each bar plot has its own significance too. We hope this blog has helped you enhance your knowledge of matplotlib bar plot in Python. If you want to learn more, then check out our articles.

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!