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
Plot two horizontal bar charts sharing the same Y-axis in Python Matplotlib
To plot two horizontal bar charts sharing the same Y-axis in Python Matplotlib, we can use sharey=ax1 in the subplot() method and barh() for creating horizontal bars. This technique is useful for comparing two related datasets side by side.
Steps
- Create lists for data points
- Create a new figure using
figure()method - Add the first subplot using
subplot()method at index 1 - Plot horizontal bar chart on the first axis using
barh()method - Add the second subplot at index 2, sharing the Y-axis with the first subplot
- Plot the second horizontal bar chart on the shared axis
- Display the figure using
show()method
Example
Here's how to create two horizontal bar charts with a shared Y-axis ?
import matplotlib.pyplot as plt
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Sample data
y = [3, 1, 5]
x1 = [10, 7, 3]
x2 = [9, 5, 1]
# Create figure
fig = plt.figure()
# First subplot
ax1 = plt.subplot(121)
ax1.barh(y, x1, align='center', color='red', edgecolor='black')
ax1.set_title('Dataset 1')
# Second subplot sharing Y-axis with first
ax2 = plt.subplot(122, sharey=ax1)
ax2.barh(y, x2, align='center', color='green', edgecolor='black')
ax2.set_title('Dataset 2')
plt.show()
The output shows two horizontal bar charts positioned side by side, both using the same Y-axis scale ?
Two horizontal bar charts displayed side by side with shared Y-axis values [1, 3, 5] Left chart: red bars with values [10, 7, 3] Right chart: green bars with values [9, 5, 1]
Key Parameters
| Parameter | Description | Example Value |
|---|---|---|
sharey |
Share Y-axis with another subplot | ax1 |
align |
Alignment of bars | 'center' |
color |
Bar fill color |
'red', 'green'
|
edgecolor |
Bar border color | 'black' |
Benefits of Shared Y-Axis
Using sharey=ax1 ensures both charts use the same Y-axis scale, making it easier to compare values between the two datasets. The Y-axis labels appear only on the left chart to avoid duplication.
Conclusion
Shared Y-axis horizontal bar charts in Matplotlib allow effective side-by-side comparison of datasets. Use sharey parameter in subplot() and barh() method to create professional comparative visualizations.
