0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Create Horizontal Bar Chart in Matplotlib Easily

To create a horizontal bar chart in matplotlib, use the barh() function, which plots bars horizontally. You provide the positions on the y-axis and the bar lengths as arguments to barh().
๐Ÿ“

Syntax

The basic syntax for creating a horizontal bar chart is:

  • plt.barh(y_positions, bar_lengths, **options)

Here, y_positions is a list or array of positions on the y-axis where bars will be placed, and bar_lengths is the list or array of values that determine the length of each bar horizontally.

You can add optional parameters like color, height (thickness of bars), and tick_label (labels for each bar).

python
plt.barh(y_positions, bar_lengths, color='blue', height=0.5, tick_label=labels)
๐Ÿ’ป

Example

This example shows how to create a simple horizontal bar chart with labeled bars and custom colors.

python
import matplotlib.pyplot as plt

labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
values = [10, 15, 7, 12]
y_positions = range(len(labels))

plt.barh(y_positions, values, color='skyblue', height=0.6, tick_label=labels)
plt.xlabel('Quantity')
plt.title('Fruit Quantity')
plt.show()
Output
A horizontal bar chart with four bars labeled Apples, Bananas, Cherries, and Dates on the y-axis and their quantities on the x-axis.
โš ๏ธ

Common Pitfalls

  • Mixing up bar() and barh(): bar() creates vertical bars, while barh() creates horizontal bars.
  • Not matching the length of y_positions and bar_lengths causes errors.
  • Forgetting to set tick_label results in unlabeled bars, which can confuse viewers.
  • Using incorrect axis labels can mislead interpretation.
python
import matplotlib.pyplot as plt

# Wrong: Using bar() for horizontal bars
labels = ['A', 'B', 'C']
values = [5, 7, 3]
plt.bar(labels, values)  # This creates vertical bars
plt.show()

# Right: Using barh() for horizontal bars
plt.barh(labels, values)
plt.show()
Output
First plot: vertical bars labeled A, B, C with heights 5, 7, 3. Second plot: horizontal bars labeled A, B, C with lengths 5, 7, 3.
๐Ÿ“Š

Quick Reference

Here is a quick summary of key parameters for plt.barh():

ParameterDescription
y_positionsPositions of bars on the y-axis (list or array)
bar_lengthsLengths of each horizontal bar (list or array)
colorColor of the bars (string or list)
heightThickness of each bar (float, default 0.8)
tick_labelLabels for each bar on y-axis (list)
align'center' or 'edge' alignment of bars
โœ…

Key Takeaways

Use plt.barh() to create horizontal bar charts in matplotlib.
Provide y-axis positions and bar lengths as the first two arguments.
Set tick_label to add labels to each bar for clarity.
Avoid mixing bar() and barh() to prevent confusion.
Customize colors and bar thickness with color and height parameters.