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
Selected Reading
How do I plot hatched bars using Pandas and Matplotlib?
Hatched bars add visual texture and pattern to bar charts, making them more distinguishable and accessible. Using Pandas with Matplotlib, you can easily create hatched bar plots by setting hatch patterns on each bar patch.
Basic Hatched Bar Plot
Here's how to create a simple hatched bar chart ?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
df = pd.DataFrame(np.random.rand(5, 2), columns=['Series A', 'Series B'])
ax = plt.figure().add_subplot(111)
# Create bar plot
bars = df.plot(ax=ax, kind='bar')
# Define hatch patterns
hatches = ["///", "\\", "|||", "---", "+++", "xxx", "ooo", "..."]
# Apply hatches to each bar
for i, patch in enumerate(bars.patches):
patch.set_hatch(hatches[i % len(hatches)])
plt.title("Hatched Bar Chart")
plt.ylabel("Values")
plt.show()
Using Specific Hatch Patterns for Each Series
For better control, assign specific patterns to each data series ?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = {'Product A': [20, 35, 30, 35, 27],
'Product B': [25, 32, 34, 20, 25],
'Product C': [15, 25, 18, 30, 22]}
df = pd.DataFrame(data, index=['Q1', 'Q2', 'Q3', 'Q4', 'Q5'])
# Create the plot
ax = df.plot(kind='bar', figsize=(10, 6))
# Define specific hatches for each series
series_hatches = ['///', '\\\', '|||']
# Apply hatches by series
num_series = len(df.columns)
for i, patch in enumerate(ax.patches):
series_index = i % num_series
patch.set_hatch(series_hatches[series_index])
plt.title("Quarterly Sales by Product")
plt.xlabel("Quarter")
plt.ylabel("Sales (in thousands)")
plt.xticks(rotation=45)
plt.legend(title="Products")
plt.tight_layout()
plt.show()
Available Hatch Patterns
Matplotlib supports various hatch patterns that can be combined ?
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
categories = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
values = [23, 45, 56, 78, 32, 67, 89, 12]
df = pd.DataFrame({'Values': values}, index=categories)
# Create plot
ax = df.plot(kind='bar', figsize=(12, 6), color='lightblue', edgecolor='black')
# Different hatch patterns
patterns = ['/', '\', '|', '-', '+', 'x', 'o', '.']
# Apply different hatch to each bar
for i, patch in enumerate(ax.patches):
patch.set_hatch(patterns[i])
plt.title("Different Hatch Patterns")
plt.xlabel("Categories")
plt.ylabel("Values")
# Add pattern labels
for i, (cat, val) in enumerate(zip(categories, values)):
ax.text(i, val + 1, f"'{patterns[i]}'", ha='center', fontsize=10)
plt.tight_layout()
plt.show()
Common Hatch Patterns
| Pattern | Symbol | Description |
|---|---|---|
/ |
Forward slash | Diagonal lines (bottom-left to top-right) |
\ |
Backslash | Diagonal lines (top-left to bottom-right) |
| |
Pipe | Vertical lines |
- |
Dash | Horizontal lines |
+ |
Plus | Crossed lines |
x |
X | Diagonal crosses |
. |
Dot | Small dots |
Conclusion
Hatched bars enhance data visualization by adding texture patterns to distinguish between different data series. Use patch.set_hatch() to apply patterns and combine multiple characters for denser hatching effects.
Advertisements
