The Wayback Machine - https://web.archive.org/web/20240910173103/https://www.geeksforgeeks.org/bar-plot-in-matplotlib/
Open In App

Bar Plot in Matplotlib

Last Updated : 12 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories.
 

Creating a bar plot


The matplotlib API in Python provides the bar() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the bar() function to be used with the axes is as follows:-

plt.bar(x, height, width, bottom, align)


The function creates a bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the bar plot, which represents the number of students enrolled in different courses of an institute. 
 

Python
import numpy as np
import matplotlib.pyplot as plt 

 
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30, 
        'Python':35}
courses = list(data.keys())
values = list(data.values())
 
fig = plt.figure(figsize = (10, 5))

# creating the bar plot
plt.bar(courses, values, color ='maroon', 
        width = 0.4)

plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()

Output- 
 


Here plt.bar(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the X-axis, and the values as the Y-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands.
 

Customizing the bar plot

Python
import pandas as pd
from matplotlib import pyplot as plt

# Read CSV into pandas
data = pd.read_csv(r"cars.csv")
data.head()
df = pd.DataFrame(data)

name = df['car'].head(12)
price = df['price'].head(12)

# Figure Size
fig = plt.figure(figsize =(10, 7))

# Horizontal Bar Plot
plt.bar(name[0:10], price[0:10])

# Show Plot
plt.show()

Output:
 


It is observed in the above bar graph that the X-axis ticks are overlapping each other thus it cannot be seen properly. Thus by rotating the X-axis ticks, it can be visible clearly. That is why customization in bar graphs is required.

Python
import pandas as pd
from matplotlib import pyplot as plt

# Read CSV into pandas
data = pd.read_csv(r"cars.csv")
data.head()
df = pd.DataFrame(data)

name = df['car'].head(12)
price = df['price'].head(12)

# Figure Size
fig, ax = plt.subplots(figsize =(16, 9))

# Horizontal Bar Plot
ax.barh(name, price)

# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
    ax.spines[s].set_visible(False)

# Remove x, y Ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')

# Add padding between axes and labels
ax.xaxis.set_tick_params(pad = 5)
ax.yaxis.set_tick_params(pad = 10)

# Add x, y gridlines
ax.grid(b = True, color ='grey',
        linestyle ='-.', linewidth = 0.5,
        alpha = 0.2)

# Show top values 
ax.invert_yaxis()

# Add annotation to bars
for i in ax.patches:
    plt.text(i.get_width()+0.2, i.get_y()+0.5, 
             str(round((i.get_width()), 2)),
             fontsize = 10, fontweight ='bold',
             color ='grey')

# Add Plot Title
ax.set_title('Sports car and their price in crore',
             loc ='left', )

# Add Text watermark
fig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize = 12,
         color ='grey', ha ='right', va ='bottom',
         alpha = 0.7)

# Show Plot
plt.show()

Output:
 


There are many more Customizations available for bar plots.
 

Multiple bar plots


Multiple bar plots are used when comparison among the data set is to be done when one variable is changing. We can easily convert it as a stacked area bar chart, where each subgroup is displayed by one on top of the others. It can be plotted by varying the thickness and position of the bars. Following bar plot shows the number of students passed in the engineering branch:

Python
import numpy as np 
import matplotlib.pyplot as plt 

# set width of bar 
barWidth = 0.25
fig = plt.subplots(figsize =(12, 8)) 

# set height of bar 
IT = [12, 30, 1, 8, 22] 
ECE = [28, 6, 16, 5, 10] 
CSE = [29, 3, 24, 25, 17] 

# Set position of bar on X axis 
br1 = np.arange(len(IT)) 
br2 = [x + barWidth for x in br1] 
br3 = [x + barWidth for x in br2] 

# Make the plot
plt.bar(br1, IT, color ='r', width = barWidth, 
        edgecolor ='grey', label ='IT') 
plt.bar(br2, ECE, color ='g', width = barWidth, 
        edgecolor ='grey', label ='ECE') 
plt.bar(br3, CSE, color ='b', width = barWidth, 
        edgecolor ='grey', label ='CSE') 

# Adding Xticks 
plt.xlabel('Branch', fontweight ='bold', fontsize = 15) 
plt.ylabel('Students passed', fontweight ='bold', fontsize = 15) 
plt.xticks([r + barWidth for r in range(len(IT))], 
        ['2015', '2016', '2017', '2018', '2019'])

plt.legend()
plt.show() 

Output:
 


 

Stacked bar plot


Stacked bar plots represent different groups on top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going from zero to value. The following bar plot represents the contribution of boys and girls in the team.
 

Python
import numpy as np
import matplotlib.pyplot as plt

N = 5

boys = (20, 35, 30, 35, 27)
girls = (25, 32, 34, 20, 25)
boyStd = (2, 3, 4, 1, 2)
girlStd = (3, 5, 2, 3, 3)
ind = np.arange(N)   
width = 0.35  

fig = plt.subplots(figsize =(10, 7))
p1 = plt.bar(ind, boys, width, yerr = boyStd)
p2 = plt.bar(ind, girls, width,
             bottom = boys, yerr = girlStd)

plt.ylabel('Contribution')
plt.title('Contribution by the teams')
plt.xticks(ind, ('T1', 'T2', 'T3', 'T4', 'T5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('boys', 'girls'))

plt.show()

Output- 
 


Bar Plot in Matplotlib – FAQs

How to plot a bar graph in Jupyter notebook?

You can plot a bar graph in a Jupyter notebook using the matplotlib library. Here’s a basic example:

import matplotlib.pyplot as plt

# Data for plotting
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]

# Create bar plot
plt.bar(categories, values)

# Show plot
plt.show()

How do you draw a bar plot?

To draw a bar plot, you can use either matplotlib or seaborn libraries. Here’s an example using matplotlib:

import matplotlib.pyplot as plt

# Data for plotting
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]

# Create bar plot
plt.bar(categories, values)

# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')

# Show plot
plt.show()

What is the difference between a bar plot and a histogram?

  • Bar Plot: Used to display and compare the values of different discrete categories. Each bar represents a category, and the height of the bar corresponds to its value.
  • Histogram: Used to show the distribution of a continuous variable. It groups data into bins (intervals) and displays the frequency of data points in each bin.

Example of a histogram:

import matplotlib.pyplot as plt

# Data for plotting
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

# Create histogram
plt.hist(data, bins=5)

# Add labels and title
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Example')

# Show plot
plt.show()

How do I save a bar plot to a file?

You can save a bar plot to a file using the savefig() method from matplotlib:

import matplotlib.pyplot as plt

# Data for plotting
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]

# Create bar plot
plt.bar(categories, values)

# Save plot to a file
plt.savefig('bar_plot.png') # You can also use 'bar_plot.pdf', 'bar_plot.svg', etc.

# Show plot
plt.show()

How can I change the style of the bar edges in a bar plot?

You can customize the bar edges using the edgecolor and linewidth parameters in matplotlib:

 import matplotlib.pyplot as plt

# Data for plotting
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]

# Create bar plot with custom edges
plt.bar(categories, values, edgecolor='black', linewidth=2)

# Show plot
plt.show()


Previous Article
Next Article

Similar Reads

Setting Different error bar colors in bar plot in Matplotlib
Python provides us with a variety of libraries where Matplotlib is one of them. It is used for data visualization purposes. In this article, we will be setting different error bar colors in the bar plot in Matplotlib. Error bars in Matplotlib Various plots of matplotlib such as bar charts, line plots can use error bars. Error bars are used for show
5 min read
How to display the value of each bar in a bar chart using Matplotlib?
In this article, we are going to see how to display the value of each bar in a bar chart using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib - Using matplotlib.axes.Axes.text() function.Use matplotlib.pyplot.text() function. Example 1: Using matplotlib.axes.Axes.text() function: This functio
2 min read
Create a grouped bar plot in Matplotlib
In this article, we will learn how to Create a grouped bar plot in Matplotlib. Let's discuss some concepts : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduce
2 min read
Create a stacked bar plot in Matplotlib
In this article, we will learn how to Create a stacked bar plot in Matplotlib. Let's discuss some concepts: Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack.A bar plot or bar graph
3 min read
Add error bars to a Matplotlib bar plot
Prerequisites: Matplotlib In this article, we will create a bar plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. Approach:Import required python library.Making simple data.Plot u
3 min read
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
Prerequisites: PandasMatplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are
2 min read
Stacked Percentage Bar Plot In MatPlotLib
A Stacked Percentage Bar Chart is a simple bar chart in the stacked form with a percentage of each subgroup in a group. Stacked bar plots represent different groups on the top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going f
3 min read
PyQt5 - Image bar as Progress Bar
In this article we will see how to add image to bar of progress bar. We can set the background image but in order to set image to a bar we have to modify the progress bar chunk CSS, below is how normal background image and background image to a bar looks like. In order to do this below is the CSS style sheet for chunk file QProgressBar::chunk { bac
2 min read
PyQt5 - Translucent Bar of Progress Bar
In this article we will see how to make the bar translucent i.e in between opaque and transparent. The progress bar have two components one is the background which is visible when bar is not at 100% other is the bar which tells the progress, when we make bar translucent the background will be visible. In order to do this we have to change the alpha
2 min read
PyQt5 - Adding border to Bar of Progress Bar
In this article we will see how to add border to the bar of progress bar. Progress bar has basically two parts one is background and other is the bar which changes its size according to the percentage. Below is the representation of normal progress bar vs border to bar of progress bar. In order to add border to bar we have to change the CSS style s
2 min read
PyQt5 - Dotted border to bar of Progress Bar
In this article we will see how to add dotted border to the bar of progress bar. Below is the representation of normal border to bar vs the dotted border to the bar of progress bar. In order to do this we have to change the border style in the CSS style sheet, below is the style sheet code. QProgressBar { border : 1px solid black; } QProgressBar {
2 min read
PyQt5 - Multi colored border to bar of Progress Bar
In this article we see how to create the multi colored border to the bar of the progress bar. Bar is the part of progress bar which indicates the completeness. Below is the representation of border bar of progress bar vs the multi colored bar of progress bar. In order to this we have change the color of each border of bar of progress bar in CSS sty
2 min read
PyQt5 - Skin to Bar of Progress Bar
In this article we will see how to set the skin to the bar of progress bar. Skin is basically a background image but it adjust it self to the size of bar of progress bar. Below is the representation of bar of progress bar with background image and bar of progress bar with skin. In order to do this we have to change the CSS style sheet code of bar o
2 min read
PyQt5 - Gradient color Bar of Progress Bar
In this article we will see how we can create the gradient color to bar of progress bar. Gradient Color : In computer graphics, a color gradient specifies a range of position-dependent colors, usually used to fill a region. For example, many window managers allow the screen background to be specified as a gradient. The colors produced by a gradient
2 min read
Highlight a Bar in Bar Chart using Altair in Python
Data visualization is the graphical representation of data and Python comes bundled with several libraries that can be used for data visualization which makes it a popular choice among data scientists. Altair is one such data visualization library in Python. Altair API is simple, user-friendly, consistent, and built on top of Vega-Lite JSON configu
3 min read
Python | Pandas Dataframe.plot.bar
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DataFrame.plot.bar() plots the graph vertically in form of rectangular bars. Syntax : DataFrame.plot.bar(x=None, y=None, **kwds)
2 min read
How to plot Bar Graph in Python using CSV file?
CSV stands for "comma separated values", that means the values are distinguished by putting commas and newline characters. A CSV file provides a table like format that can be read by almost every spreadsheet reader like Microsoft Excel and Google Spreadsheet. A Bar Graph uses labels and values where label is the name of a particular bar and value r
2 min read
Using pandas crosstab to create a bar plot
In this article, we will discuss how to create a bar plot by using pandas crosstab in Python. First Lets us know more about the crosstab, It is a simple cross-tabulation of two or more variables. What is cross-tabulation? It is a simple cross-tabulation that help us to understand the relationship between two or more variable. It will give a clear u
3 min read
Circular Bar Plot in Python
In this guide, we'll dive into the world of circular bar plots in Python. We'll explore what they are, why they're useful, and how you can create them to add a stylish touch to your data visualization projects. What is a Circular Bar Plot?Circular bar plots, also known as radial bar charts or circular stacked bar plots, are a variation of tradition
3 min read
How to Create a Stacked Bar Plot
In this article, we will discuss how to create a stacked bar plot in Seaborn in Python. A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method. We can also pass the list of colors as we ne
2 min read
PyQtGraph - Getting Plot Item from Plot Window
In this article we will see how we can get the plot item of plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and s
2 min read
Time Series Plot or Line plot with Pandas
Prerequisite: Create a Pandas DataFrame from Lists Pandas is an open-source library used for data manipulation and analysis in Python. It is a fast and powerful tool that offers data structures and operations to manipulate numerical tables and time series. Examples of these data manipulation operations include merging, reshaping, selecting, data cl
6 min read
Pandas Scatter Plot – DataFrame.plot.scatter()
A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame. Synta
2 min read
Plot 2D data on 3D plot in Python
In this article, we will be learning about how to plot 2D data on 3D plot in Python. We will be demonstrating two methods in order to learn the concept. The first method will be using Matplotlib.pyplot.gca() function which is a pyplot module of the matplotlib library. But before that, we need to configure where are we going to create our project an
4 min read
Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
Matplotlib.axes.Axes.bar() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. Matplotlib.axes.Axes.bar() Function The Axes.bar()
2 min read
Plotting back-to-back bar charts Matplotlib
In this article, we will learn how to plot back-to-back bar charts in matplotlib in python. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It w
2 min read
Draw a horizontal bar chart with Matplotlib
Matplotlib is the standard python library for creating visualizations in Python. Pyplot is a module of Matplotlib library which is used to plot graphs and charts and also make changes in them. In this article, we are going to see how to draw a horizontal bar chart with Matplotlib. Creating a vertical bar chart Approach: Importing matplotlib.pyplot
2 min read
Change the error bar thickness in Matplotlib
Matplotlib is a Python library which is widely used by data analytics. Matplotlib.pyplot.errorbar() is a pyplot module consisting of a function which provides a MATLAB like interface. Changing Error Bar Thickness Before changing the thickness of error bar let us see what error bar is and how we can plot and use them. Error Bar: Error bars are bars
2 min read
How to change Matplotlib color bar size in Python?
Colorbar is a separate axis that provides a current colormap indicating mapping of data-points into colors. In this article, We are going to change Matplotlib color bar size in Python. There are several ways with which you can resize your color-bar or adjust its position. Let's see it one by one. Method 1: Resizing color-bar using shrink keyword ar
2 min read
Article Tags :
Practice Tags :