Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การลด Hatch Density ใน Matplotlib Bar Chart

สร้าง Custom Hatch Class เพื่อควบคุมความหนาแน่นของ Pattern (Hatch) ใน Bar Chart โดย Override ค่า Density

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Class MyHorizontalHatch 繼承จาก hatch.HorizontalHatch
  3. Override __init__ คำนวณ num_lines จาก Density
  4. ลงทะเบียน Hatch Type ใหม่
  5. สร้าง Bar Chart ใช้ Hatch 'o'
  6. แสดงผล

ตัวอย่างโค้ด


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 ที่ใช้ได้

/\|-+xoO.*
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