The Wayback Machine - https://web.archive.org/web/20241104230808/https://www.geeksforgeeks.org/matplotlib-pyplot-barh-function-in-python/
Open In App

Matplotlib.pyplot.barh() function in Python

Last Updated : 28 Jul, 2022
Summarize
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 Horizontal bar plot

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

Syntax: matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)

Some of the positional and optional parameters of the above function are described below:

Parameters Description
Y  Co-ordinates of the Y bars.
width Scalar or array like, denotes the width of the bars.
height Scalar or array like, denotes the height of the bars(default value is 0.8).
left Scalar or sequence of scalars, denotes X co-ordinates on the left sides of the bars(default value is 0).
align {‘center’, ‘edge’}aligns the base of the Y co-ordinates(default value is center).
color Scalar or array like, denotes the color of the bars.
edgecolor Scalar or array like, denotes the edge color of the bars.
linewidth Scalar or array like, denotes the width of the bar edges.
tick_label Scalar or array like, denotes the tick labels of the bars(default value is None).

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

Example 1:

Python3




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.barh(courses, values, color='maroon')
 
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()


Output :

Here plt.barh(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the Y-axis, and the values as the X-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.

Example 2:

Python3




import pandas as pd
from matplotlib import pyplot as plt
 
# Read CSV into pandas
data = pd.read_csv(r"Downloads/cars1.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.splines[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:



Similar Reads

matplotlib.axes.Axes.barh() 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.barh() Function The Axes.barh
2 min read
Matplotlib.pyplot.figimage() function in Python
Matplotlib is a widely used library in Python for plotting various graphs, as it provides very efficient ways and easy to understand methods for complex plots also. pyplot is a collection of command style functions that make matplotlib work like MATLAB. figimage() function matplotlib.pyplot.figimage() is a method for adding a non-resampled image to
2 min read
Matplotlib.pyplot.hexbin() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. Matplotlib.pyplot.hexbin() function The hexbi
2 min read
Matplotlib.pyplot.suptitle() function in Python
Matplotlib is a library in Python and it is a mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.suptitle() Function The suptitle() function in pyplot module of the matplotlib library is used to add a title to the figure. Syntax: matplotlib.pyp
3 min read
Matplotlib.pyplot.xscale() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.xscale() function The xscal
2 min read
Matplotlib.pyplot.setp() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. Matplotlib.pyplot.setp() function The setp()
2 min read
matplotlib.pyplot.semilogy() function in Python
Matplotlib is the most popular and Python-ready package that is used for visualizing the data. We use matplotlib for plotting high-quality charts, graphs, and figures. matplotlib.pyplot.semilogy() Function The matplotlib.pyplot.semilogy() function in pyplot module of matplotlib library is used to make a plot with log scaling on the y axis. Syntax:
2 min read
Matplotlib.pyplot.figlegend() function in Python
Matplotlib is a Python library used for creating, animations, and editing graphs, plots, and figures using Pyplot. Matplotlib.pyplot has many functions defined in it to use, as per the preference and requirement of the user demands. matplotlib.pyplot.figlegend() function This is used to place a legend on the figure. A legend in Matplotlib is simila
3 min read
matplotlib.pyplot.step() function in Python
The step() function designs the plot such that, it has a horizontal baseline to which the data points will be connected by vertical lines. This kind of plot is used to analyze at which points the change in Y-axis value has occurred exactly with respect to X-axis. This is very useful in discrete analysis. The step plotting can be combined with any o
4 min read
Matplotlib.pyplot.pcolor() function in Python
Matplotlib is the well-known Python package used in data visualization. Numpy is the numerical mathematics extension of Matplotlib. Matplotlib is capable of producing high-quality graphs, charts, and figures. Matplotlib produces object-oriented API for embedding plots into projects using GUI toolkits like Tkinter, wxPython, or Qt. John D. Hunter wa
2 min read
Matplotlib.pyplot.table() function in Python
Matplotlib.pyplot.table() is a subpart of matplotlib library in which a table is generated using the plotted graph for analysis. This method makes analysis easier and more efficient as tables give a precise detail than graphs. The matplotlib.pyplot.table creates tables that often hang beneath stacked bar charts to provide readers insight into the d
3 min read
Matplotlib.pyplot.text() function in Python
This function is used to add a text to the axes at location x, y in data coordinates. Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)parameters Descriptionx, y:floatThe position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.s :strThe text.fontdict : di
1 min read
Matplotlib.pyplot.fill() function in Python
Matplotlib.pyplot.fill() function is used to fill the area enclosed by polygon /curve. Syntax: matplotlib.pyplot.fill(*args, data=None, **kwargs) Parameters: *args: sequence of x, y, [color] sequence of x,y = To traverse the boundaries of the polygon or curve defined by lists of x and y positions of its nodes.color = To change the default fill colo
2 min read
Matplotlib.pyplot.colorbar() function in Python
Colorbars are a visualization of the mapping from scalar values to colors. In Matplotlib they are drawn into a dedicated axis. Note: Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which uses make_axes and Colorbar internally. As an end-user, you most likely won't have to call the methods or instantiat
2 min read
Matplotlib.pyplot.loglog() function in Python
Prerequisites: Matplotlib Matplotlib is a comprehensive library for creating interactive, static and animated visualizations in python. Using general-purpose GUI toolkits like wxPython, SciPy, Tkinter or SciPy, it provides an object-oriented API for embedding plots into applications. Matplotlib.pyplot is a collection of functions that makes Matplot
2 min read
Matplotlib.pyplot.subplot() function in Python
Prerequisites: matplotlib subplot() function adds subplot to a current figure at the specified grid position. It is similar to the subplots() function however unlike subplots() it adds one subplot at a time. So to create multiple plots you will need several lines of code with the subplot() function. Another drawback of the subplot function is that
2 min read
Matplotlib.pyplot.margins() function in Python
Prerequisites: Matplotlib Matplotlib.pyplot.margins() is a function used to set the margins of the x and y axes. All input parameters must be a float that too within the range [0, 1]. We cannot pass both positional and keyword arguments at once as that will raise a TypeError. The padding added to each limit of the axes is the margin times the data
2 min read
Matplotlib.pyplot.plot() function in Python
Matplotlib is a powerful Python library that serves as a numerical and mathematical extension for the NumPy library. One of its key components is Pyplot, which offers a state-based interface to the Matplotlib module, presenting users with a familiar MATLAB-like environment. Through Matplotlib.pyplot.plot() function in Python, users can effortlessly
5 min read
Matplotlib.pyplot.plot_date() function in Python
Matplotlib is a module package or library in Python which is used for data visualization. Pyplot is an interface to a Matplotlib module that provides a MATLAB-like interface. The matplotlib.pyplot.plot_date() function is like the regular plot() function, but it's tailored for showing data over dates. Think of it as a handy tool for visualizing even
3 min read
Matplotlib.pyplot.broken_barh() in Python
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. matplotlib.pyplot.broken_barh() The function broken_barh() is used to Plot a horizontal sequence of rectan
2 min read
Matplotlib.pyplot.axis() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. matplotlib.pyplot.axis() This function is us
1 min read
Matplotlib.pyplot.get_fignums() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.get_fignums() method The ge
2 min read
Python | Matplotlib.pyplot ticks
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 was introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge
3 min read
Matplotlib.pyplot.waitforbuttonpress() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.waitforbuttonpress() method
2 min read
Matplotlib.pyplot.streamplot() in Python
Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is: ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing) Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each p
7 min read
Matplotlib.pyplot.ylim() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.ylim() Function The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes. Syntax
2 min read
matplotlib.pyplot.arrow() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. It provides MATLAB like interface only difference is that it uses Python and is open source. mat
2 min read
Matplotlib.pyplot.ylabel() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. matplotlib.pyplot.ylabel() This function sets the label for the y-axis of the plot. Syntax: matp
2 min read
Matplotlib.pyplot.acorr() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function The acorr() function in pyplot module of matplotlib library is used to plot the autocorrelation of x (array-like). Synta
2 min read
matplotlib.pyplot.angle_spectrum() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function: The angle_spectrum() function in pyplot module of matplotlib library is used to plot the angle spectrum. Generally, it
2 min read
three90RightbarBannerImg