0
0
Matplotlibdata~5 mins

Horizontal bar chart with plt.barh in Matplotlib

Choose your learning style9 modes available
Introduction

A horizontal bar chart helps you compare values across categories using bars that go from left to right. It is easy to read when category names are long or when you want to show data horizontally.

Comparing sales numbers for different products with long names.
Showing survey results where categories have long labels.
Visualizing time spent on tasks where horizontal layout fits better.
Displaying rankings or scores in a clear horizontal format.
Syntax
Matplotlib
plt.barh(y, width, height=0.8, left=None, *, align='center', **kwargs)

y is the position of bars on the vertical axis (usually categories).

width is the length of each bar (the data values).

Examples
Basic horizontal bar chart with categories on the y-axis and values as bar lengths.
Matplotlib
import matplotlib.pyplot as plt

categories = ['Apples', 'Bananas', 'Cherries']
values = [10, 15, 7]
plt.barh(categories, values)
plt.show()
Horizontal bars with custom color and thinner bars using height.
Matplotlib
plt.barh(['A', 'B', 'C'], [5, 8, 3], color='skyblue', height=0.5)
plt.show()
Using numeric positions for bars and setting labels with tick_label.
Matplotlib
positions = [0, 1, 2]
values = [4, 9, 6]
labels = ['X', 'Y', 'Z']
plt.barh(positions, values, tick_label=labels)
plt.show()
Sample Program

This program creates a horizontal bar chart showing quantities of different fruits. It adds a title and axis labels for clarity.

Matplotlib
import matplotlib.pyplot as plt

# Data
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
quantities = [25, 40, 15, 10]

# Create horizontal bar chart
plt.barh(fruits, quantities, color='green')

# Add title and labels
plt.title('Fruit Quantities')
plt.xlabel('Quantity')
plt.ylabel('Fruit')

# Show the plot
plt.show()
OutputSuccess
Important Notes

You can customize colors, bar height, and labels easily with parameters.

Horizontal bars are good when category names are long or many.

Use plt.bar for vertical bars and plt.barh for horizontal bars.

Summary

Horizontal bar charts show data with bars going left to right.

Use plt.barh with categories on y-axis and values as bar lengths.

Customize appearance with colors, bar height, and labels.