Python Matplotlib Bar Plot
In this article, you will learn about the Python Matplotlib Bar Plot.
Data exploration is the initial step in data analysis. Data exploration can use a combination of manual methods and automated tools such as data visualizations, charts, and diagrams. One of the important diagrams is the bar plot, which is widely used in many presentations. The Bar plot represents data in the rectangular bars with heights proportional to the values that they represent. It is used to compare things between different groups or to track changes over time. It shows the relationship between a numeric and a categorical variable. It can also display values for several levels of grouping. The bars can be plotted vertically or horizontally. Bar graphs are best when there are big changes in data over time. Matplotlib provides the bar() method to plot a bar graph.
Syntax of Bar Plot
matplotlib.pyplot.bar(x, height, width, bottom, align)
x - It specifies the sequence of scalars. The x coordinates of bar.
height - It specifies a scalar or a sequence of scalars. The height of the bars.
width (optional)- The width of the bars(by default 0.8).
bottom (optional)- The y coordinate(s) of the bars bases.
align (optional)- Alignment of the bars to the x coordinates.
The function returns a Matplotlib container object with all bars.
Python Basic Example of Bar Graph
Here is a very basic bar plot -
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar([1, 2, 3, 4, 5, 6], [4, 3, 7, 9, 5, 2])
plt.show()
The above code returns the following output -
Horizontal Bar Plot
The barh() function is used to make a horizontal bar plot. The bars are positioned at y with the given alignment. Here is a simple example of a horizontal bar plot that plots the temperature of different cities -
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
city = ['Dhanbad', 'Bokaro', 'Ranchi', 'Koderma', 'Giridih']
temp = [35,37,32,33,38]
ax.barh(city,temp,0.3)
plt.show()
Set Label Name, Title & Color of the Bar Plot
The above-mentioned bar plots are very basic. So, in the given example, you will learn to add the label name, the title of the plot, and set the color of the bar. Here, we have also used the ggplot style sheet. The ggplot is a plotting system for Python based on R's ggplot2 and the Grammar of Graphics. It is built for making professional looking plots quickly with minimal code.
import matplotlib.pyplot as plt
plt.style.use('ggplot')
city = ['Dhanbad', 'Bokaro', 'Ranchi', 'Koderma', 'Giridih']
temp = [35,37,32,33,38]
x_pos = [i for i, _ in enumerate(city)]
plt.bar(city,temp,0.3,color='red')
plt.ylabel("Temperature")
plt.xlabel("City")
plt.title("Temperature of Jhar Popular Cities")
plt.show()
Multiple Bar Plots
A multiple bar plot is plot that has multiple bars for each category. In this, we can compare as many sets of data as you want. The process for creating a multiple bar graph is the same as creating any other bar graph, only you will have to set different colors to represent different sets of data.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
state = ['Delhi', 'MP', 'UP', 'Tamil', 'Assam']
women_champion = [35,37,32,33,38]
men_champion = [30,22,40,42,35]
inv = np.arange(5)
x_pos = [i for i, _ in enumerate(state)]
plt.bar(inv,women_champion,0.25,color='red')
plt.bar(inv + 0.25,men_champion,0.25,color='blue')
plt.ylabel("Champions")
plt.xlabel("States")
plt.title("Champions of Different States")
plt.xticks(inv + 0.25 / 2, state)
plt.show()
The above code returns the following output -
Matplotlib Stacked Bar Chart
A stacked bar chart is a visual representation of data. It uses the length of two or more stacked bars to represent the components of a total quantitative value across a range of different categorical values. Here is a very simple example of a stacked bar chart -
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
state = ['Delhi', 'MP', 'UP', 'Tamil', 'Assam']
gold_champion = np.array([32, 15, 12, 29, 25])
silver_champion = np.array([35, 20, 28, 21, 10])
bronze_champion = np.array([40, 35, 29, 10, 27])
inv = np.arange(5)
inv = [i for i, _ in enumerate(state)]
plt.bar(inv,gold_champion,0.25,color='red',bottom=silver_champion+bronze_champion)
plt.bar(inv,silver_champion,0.25,color='blue',bottom=bronze_champion)
plt.bar(inv,bronze_champion,0.25,color='green')
plt.ylabel("Champions")
plt.xlabel("States")
plt.title("Champions of Different States")
plt.xticks(inv, state)
plt.show()
The output of this code is shown in the following image -
Related Articles
Simple Matplotlib Animation ExampleMatplotlib Pie Chart
Python Line Plot Using Matplotlib
Python Matplotlib 3D Plot
How to save figure in matplotlib pyplot
Python Matplotlib Scatter Plot
Python Pandas Plotting
How to capture a video in Python OpenCV and save
Python OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human detection OpenCV
Face Recognition OpenCV Source Code
Canny Edge Detector OpenCV Python
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization
Python OpenCV Histogram of Color Image
Python OpenCV Histogram of Grayscale Image
Python OpenCV Image Filtering
Python OpenCV ColorMap
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples