0
0
Matplotlibdata~5 mins

Horizontal grouped bars in Matplotlib

Choose your learning style9 modes available
Introduction

Horizontal grouped bars help compare different groups side by side using horizontal bars. They make it easy to see differences across categories.

Comparing sales of different products across several months.
Showing survey results for multiple questions side by side.
Visualizing test scores of students in different subjects.
Comparing expenses across departments in a company.
Syntax
Matplotlib
import matplotlib.pyplot as plt

labels = ['Group1', 'Group2', 'Group3']
values1 = [10, 20, 30]
values2 = [15, 25, 35]

import numpy as np

bar_width = 0.35
indices = np.arange(len(labels))

plt.barh(indices, values1, bar_width, label='Set 1')
plt.barh(indices + bar_width, values2, bar_width, label='Set 2')

plt.yticks(indices + bar_width / 2, labels)
plt.legend()
plt.show()

Use barh() to create horizontal bars.

Shift the bars on the y-axis by bar width to group them side by side.

Examples
Two groups of horizontal bars with labels X, Y, Z on y-axis.
Matplotlib
plt.barh([0, 1, 2], [5, 10, 15], 0.4, label='A')
plt.barh([0.4, 1.4, 2.4], [7, 12, 17], 0.4, label='B')
plt.yticks([0.2, 1.2, 2.2], ['X', 'Y', 'Z'])
plt.legend()
plt.show()
Grouped bars comparing two years for fruit sales.
Matplotlib
labels = ['Apples', 'Bananas']
values1 = [30, 40]
values2 = [35, 45]
indices = np.arange(len(labels))
plt.barh(indices, values1, 0.3, label='2019')
plt.barh(indices + 0.3, values2, 0.3, label='2020')
plt.yticks(indices + 0.15, labels)
plt.legend()
plt.show()
Sample Program

This program shows student scores in three subjects for two years using horizontal grouped bars.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['Math', 'Science', 'English']
scores_2023 = [88, 92, 85]
scores_2024 = [90, 95, 87]

bar_width = 0.35
indices = np.arange(len(labels))

plt.barh(indices, scores_2023, bar_width, label='2023')
plt.barh(indices + bar_width, scores_2024, bar_width, label='2024')

plt.yticks(indices + bar_width / 2, labels)
plt.xlabel('Scores')
plt.title('Student Scores by Subject and Year')
plt.legend()
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Make sure to shift the bars on the y-axis by the bar width to avoid overlap.

Use plt.yticks() to set the category labels in the middle of grouped bars.

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

Summary

Horizontal grouped bars show side-by-side comparisons using horizontal bars.

Use barh() and shift bars on y-axis to group them.

Set y-axis ticks to label groups clearly.