Bar charts are one of the most common and effective types of plots used to visualize categorical data. With Matplotlib, creating and customizing bar charts is straightforward and highly flexible.
This article walks you through creating vertical and horizontal bar charts, customizing colors and labels, plotting grouped bars, and more—with working examples and best practices.
What Is a Bar Chart?
A bar chart represents data with rectangular bars. The length or height of each bar corresponds to the value of the category.
Matplotlib supports two main types:
-
plt.bar()
for vertical bars -
plt.barh()
for horizontal bars
Basic Bar Chart in Matplotlib
Example
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D']
values = [10, 24, 36, 18]
plt.bar(categories, values)
plt.title("Basic Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.grid(axis='y')
plt.show()
Customizing Bar Appearance
Bar Color
plt.bar(categories, values, color='skyblue')
Edge Color and Line Width
plt.bar(categories, values, edgecolor='black', linewidth=1.2)
Bar Width
plt.bar(categories, values, width=0.5) # 1.0 is full width
Horizontal Bar Chart
Use barh()
instead of bar()
:
plt.barh(categories, values, color='lightgreen')
plt.xlabel("Values")
plt.ylabel("Categories")
plt.title("Horizontal Bar Chart")
plt.grid(axis='x')
plt.show()
Grouped Bar Chart
Used to compare subcategories side-by-side.
Example:
import numpy as np
labels = ['Q1', 'Q2', 'Q3', 'Q4']
product_A = [10, 15, 20, 25]
product_B = [12, 18, 22, 28]
x = np.arange(len(labels)) # label locations
width = 0.35 # width of the bars
fig, ax = plt.subplots()
ax.bar(x - width/2, product_A, width, label='Product A')
ax.bar(x + width/2, product_B, width, label='Product B')
ax.set_xlabel('Quarter')
ax.set_ylabel('Sales')
ax.set_title('Quarterly Sales Comparison')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
plt.tight_layout()
plt.show()
Adding Labels, Titles & Grid
plt.title("Sales Bar Chart")
plt.xlabel("Products")
plt.ylabel("Units Sold")
plt.grid(axis='y', linestyle='--', alpha=0.7)
Annotate Bars with Data Labels
Example:
bars = plt.bar(categories, values)
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, yval + 0.5, yval, ha='center', va='bottom')
Color Mapping Bars by Value
import matplotlib.cm as cm
colors = cm.viridis([v / max(values) for v in values])
plt.bar(categories, values, color=colors)
Sorting Bars
Sorted bar charts make comparisons easier:
sorted_data = sorted(zip(categories, values), key=lambda x: x[1], reverse=True)
categories, values = zip(*sorted_data)
plt.bar(categories, values)
Full Example: Custom Bar Chart
import matplotlib.pyplot as plt
products = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [120, 90, 150, 70]
plt.figure(figsize=(8, 5))
bars = plt.bar(products, sales, color='coral', edgecolor='black')
# Add data labels
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, yval + 3, f'{yval}', ha='center')
plt.title("Fruit Sales")
plt.xlabel("Fruits")
plt.ylabel("Units Sold")
plt.grid(axis='y', linestyle='--')
plt.tight_layout()
plt.show()
Tips for Working with Bar Charts
Tip | Why It Helps |
---|---|
Use plt.tight_layout() |
Avoids label clipping |
Use plt.grid(axis='y') |
Improves readability |
Use plt.barh() |
For long category names |
Add plt.text() |
Shows exact values |
Sort data | Easier visual comparison |
⚠️ Common Pitfalls
Pitfall | Solution |
---|---|
Bars overlap in grouped chart | Use width and position offset |
Labels cut off | Use plt.tight_layout() or figsize |
Bars same color | Use color or colormap |
Poor axis alignment | Use set_xticks() and set_xticklabels() |
Summary Table
Function | Purpose |
---|---|
plt.bar() |
Vertical bar chart |
plt.barh() |
Horizontal bar chart |
color= |
Set bar color |
edgecolor= |
Outline color |
width= |
Bar width |
label= |
Legend label |
plt.text() |
Add data label |
Conclusion
Matplotlib’s bar charts are an excellent tool for comparing categorical values. With built-in options to group, stack, or format bars, you can create professional-looking charts suitable for reports, dashboards, and presentations.
What’s Next?
-
Create stacked bar charts
-
Plot bar charts from Pandas DataFrames
-
Animate bar charts using FuncAnimation
-
Create interactive bar charts with Plotly