การดึงสีของเส้นที่พล็อตล่าสุด
ใช้ get_color() method บน Line2D objects ที่คืนจาก plot()
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- สร้างข้อมูล x, y ด้วย numpy
- พล็อตหลายเส้นพร้อมกัน plt.plot(x, y, x, y**2, x, y**3)
- ตั้งค่า legend
- ดึงสีแต่ละเส้นด้วย p[0].get_color(), p[1].get_color(), p[2].get_color()
- แสดงผลและพิมพ์สีใน console
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(10)
y = np.arange(10)
p = plt.plot(x, y, x, y ** 2, x, y ** 3)
plt.legend([p[0], p[1], p[2]], ["$y=x$", "$y=x^2$", "$y=x^3$"])
print("Color of the first plot: ", p[0].get_color())
print("Color of the second plot: ", p[1].get_color())
print("Color of the third plot: ", p[2].get_color())
plt.show()
ผลลัพธ์ Console
Color of the first plot: #1f77b4
Color of the second plot: #ff7f0e
Color of the third plot: #2ca02c
คำอธิบาย
plot() คืนค่า list ของ Line2D objects ใช้ get_color() ดึงสีในรูปแบบ hex