สร้าง Custom Hatch Class เพื่อควบคุมความหนาแน่นของ Pattern (Hatch) ใน Bar Chart โดย Override ค่า Density
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Class
MyHorizontalHatch繼承จากhatch.HorizontalHatch - Override
__init__คำนวณnum_linesจาก Density - ลงทะเบียน Hatch Type ใหม่
- สร้าง Bar Chart ใช้ Hatch 'o'
- แสดงผล
ตัวอย่างโค้ด
from matplotlib import pyplot as plt, hatch
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
class MyHorizontalHatch(hatch.HorizontalHatch):
def __init__(self, hatch, density):
char_count = hatch.count('o')
if char_count > 0:
# ปรับ density: ค่ายิ่งน้อย = หนาแน่นน้อยลง
self.num_lines = int((1.0 / char_count) * density)
else:
self.num_lines = 0
self.num_vertices = self.num_lines * 2
super().__init__(hatch, density)
# ลงทะเบียน Hatch ใหม่
hatch._hatch_types.append(MyHorizontalHatch)
fig = plt.figure()
ax1 = fig.add_subplot(111)
x = [3, 6, 1]
y = [4, 6, 1]
# ใช้ hatch='o' กับ density ที่ปรับแล้ว
ax1.bar(x, y, color='green', edgecolor='red', hatch="o", lw=1., zorder=0)
plt.show()
Hatch Patterns ที่ใช้ได้
| Pattern | รูปแบบ |
|---|---|
| Diagonal lines | |
| Diagonal lines (opposite) | |
| Vertical lines | |
| Horizontal lines | |
| Crosshatch | |
| Diagonal crosshatch | |
| Circles | |
| Large circles | |
| Dots | |
| Stars |
ผลลัพธ์
Bar Chart 3 แท่ง สีเขียว ขอบสีแดง มี Pattern วงกลม (o) ที่ความหนาแน่นลดลงตาม Custom Class