ใช้เมธอด axhline() เพื่อวาดเส้นเกณฑ์
ขั้นตอนการทำงาน
- กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
- กำหนดตัวแปร threshold
- สร้างรายการค่า bars
- หาค่าที่ต่ำกว่าและสูงกว่าเกณฑ์
- สร้าง figure และชุด subplots ด้วย subplots()
- พล็อตแท่งด้วย x, a_threshold และ b_threshold
- เพิ่มเส้นแนวนอนข้ามแกนด้วย axhline()
- ใช้เมธอด show() เพื่อแสดงรูปภาพ
ตัวอย่างโค้ด
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()
ผลลัพธ์
