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

Python Matplotlib - ตั้ง Label ให้ Horizontal Lines (hlines)

ใช้ plt.hlines() วาดเส้นแนวนอน แล้วเพิ่ม Label ด้วย plt.text() ที่ปลายเส้น

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

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Horizontal line y=1, x from 1 to 4, orange
plt.hlines(y=1, xmin=1, xmax=4, lw=7, color='orange')
plt.text(4, 1, 'y=1', ha='left', va='center')

# Horizontal line y=2, x from 2 to 5, red
plt.hlines(y=2, xmin=2, xmax=5, lw=7, color='red')
plt.text(2, 2, 'y=2', ha='right', va='center')

plt.show()

คำอธิบาย

  • hlines(y, xmin, xmax) วาดเส้นแนวนอนที่ y จาก xmin ถึง xmax
  • lw = Line Width
  • plt.text(x, y, 'label', ha, va) ใส่ข้อความ: ha=Horizontal Align, va=Vertical Align
  • เส้นแรก: Label ด้านขวา (ha='left' เพราะ x=4 เป็นปลายขวา)
  • เส้นที่สอง: Label ด้านซ้าย (ha='right' เพราะ x=2 เป็นปลายซ้าย)