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()andbarh():bar()creates vertical bars, whilebarh()creates horizontal bars. - Not matching the length of
y_positionsandbar_lengthscauses errors. - Forgetting to set
tick_labelresults 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():
| Parameter | Description |
|---|---|
| y_positions | Positions of bars on the y-axis (list or array) |
| bar_lengths | Lengths of each horizontal bar (list or array) |
| color | Color of the bars (string or list) |
| height | Thickness of each bar (float, default 0.8) |
| tick_label | Labels 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.