Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Giảm mật độ hatch (kết cấu) trong Matplotlib

Để giảm mật độ hatch (kết cấu vẽ) trong Matplotlib:

  • Thiết lập kích thước figure và padding
  • Tạo class hatch ngang tùy chỉnh để ghi đè density
  • Thêm class hatch vào registry
  • Tạo figure và subplot
  • Tạo dữ liệu cho bar plot
  • Vẽ bar plot với hatch='o', color='green', edgecolor='red'
  • Hiển thị bằng show()

Ví dụ mã nguồn

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:
            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_types.append(MyHorizontalHatch)

fig = plt.figure()
ax1 = fig.add_subplot(111)
x = [3, 6, 1]
y = [4, 6, 1]
ax1.bar(x, y, color='green', edgecolor='red', hatch="o", lw=1., zorder=0)
plt.show()

Kết quả

Biểu đồ cột với hatch pattern 'o' (chấm) nhưng mật độ thấp hơn mặc định.

Giảm mật độ hatch (kết cấu) trong Matplotlib

Lưu ý: Cách này khá phức tạp. Đơn giản hơn: dùng pattern ít ký tự hơn (ví dụ: hatch='/' thay vì hatch='////') hoặc vẽ thủ công với fill_between.