Để vẽ bar chart với đường ngưỡng ngang, dùng axhline() và tách cột thành phần dưới/ngưỡng bằng np.maximum/minimum.
Các bước
- Thiết lập figure size và autolayout.
- Khởi tạo threshold và mảng values.
- Tính phần dưới ngưỡng: b_threshold = np.minimum(values, threshold).
- Tính phần trên ngưỡng: a_threshold = np.maximum(values - threshold, 0).
- Vẽ stacked bar: cột xanh (dưới), cột vàng (trên) với bottom=b_threshold.
- Vẽ đường ngưỡng: plt.axhline(threshold, color='red', ls='dotted').
- Hiển thị bằng show().
Ví dụ
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
threshold = 10
values = np.array([8.0, 10.0, 15.0, 9.0, 12.0])
x = range(len(values))
a_threshold = np.maximum(values - threshold, 0)
b_threshold = np.minimum(values, threshold)
fig, ax = plt.subplots()
ax.bar(x, b_threshold, 0.35, color="blue")
ax.bar(x, a_threshold, 0.35, color="yellow", bottom=b_threshold)
plt.axhline(threshold, color='red', ls='dotted')
plt.show()
Kết quả
