Để thêm mẫu vân (hatch pattern) cho các cột trong biểu đồ cột Pandas/Matplotlib:
Các bước
- Thiết lập figure size và autolayout.
- Tạo DataFrame ngẫu nhiên 2 cột.
- Thêm axes subplot bằng add_subplot(111).
- Vẽ bar chart bằng df.plot(ax=ax, kind='bar').
- Tạo danh sách các mẫu hatch (*, /, o, x).
- Lấy các patch cột bằng bars.patches.
- Duyệt patches và gán hatch ngẫu nhiên bằng set_hatch().
- Hiển thị bằng show().
Ví dụ
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
ax = plt.figure().add_subplot(111)
bars = df.plot(ax=ax, kind='bar')
hatches = ["*", "/", "o", "x"]
for patch in bars.patches:
patch.set_hatch(hatches[np.random.randint(10)%len(hatches)])
plt.show()
Kết quả
