Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot multiple horizontal bars in one chart with matplotlib?
To plot multiple horizontal bars in one chart with matplotlib, you can use the barh() method with different y-positions for each data series. This creates grouped horizontal bar charts that allow easy comparison between multiple datasets.
Steps
Import the required libraries: matplotlib, numpy, and pandas (if needed)
Set the figure size and layout parameters
Create arrays for bar positions and define bar width
Use
barh()to create horizontal bars with offset positionsConfigure y-axis ticks and labels
Add a legend to distinguish between data series
Display the plot using
show()
Example
Here's how to create a horizontal bar chart with two data series ?
import matplotlib.pyplot as plt
import numpy as np
# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Array for horizontal bar's position
ind = np.array([0, 1, 2])
# Bar's width
width = 0.4
fig, ax = plt.subplots()
# Horizontal bar plot
ax.barh(ind, np.array([4, 3, 5]), width, color='orange', label='Series N')
ax.barh(ind + width, np.array([2, 5, 2]), width, color='blue', label='Series M')
# Set Y-axis ticks and ticklabels
ax.set(yticks=ind + width/2, yticklabels=np.array(['Category A', 'Category B', 'Category C']),
ylim=[-0.5, len(ind)])
# Legend at the upper right corner
ax.legend(loc='upper right')
# Add labels
ax.set_xlabel('Values')
ax.set_ylabel('Categories')
ax.set_title('Multiple Horizontal Bar Chart')
# Display the plot
plt.show()
Output
The code produces a horizontal bar chart with two data series displayed side by side ?
Advanced Example with More Data Series
You can add more data series by adjusting the y-positions ?
import matplotlib.pyplot as plt
import numpy as np
# Data
categories = ['Product A', 'Product B', 'Product C', 'Product D']
q1_sales = [20, 35, 30, 25]
q2_sales = [25, 30, 35, 30]
q3_sales = [30, 25, 20, 35]
# Position settings
y_pos = np.arange(len(categories))
bar_height = 0.25
# Create the plot
fig, ax = plt.subplots(figsize=(10, 6))
# Create horizontal bars
bars1 = ax.barh(y_pos - bar_height, q1_sales, bar_height, label='Q1', color='skyblue')
bars2 = ax.barh(y_pos, q2_sales, bar_height, label='Q2', color='orange')
bars3 = ax.barh(y_pos + bar_height, q3_sales, bar_height, label='Q3', color='lightgreen')
# Customize the chart
ax.set_xlabel('Sales (in thousands)')
ax.set_ylabel('Products')
ax.set_title('Quarterly Sales Comparison')
ax.set_yticks(y_pos)
ax.set_yticklabels(categories)
ax.legend()
# Add grid for better readability
ax.grid(axis='x', alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
y_pos |
Vertical position of bars | np.array([0, 1, 2]) |
width/height |
Bar thickness | 0.4 |
color |
Bar color |
'orange', 'blue'
|
label |
Legend label | 'Series A' |
Conclusion
Use barh() with offset y-positions to create multiple horizontal bar series. Adjust the bar width and positioning to prevent overlap and ensure clear visualization of your data comparisons.
