การปรับความหนาขอบกรอบ Legend (Legend Frame) ใน Matplotlib ทำได้โดยเข้าถึง Legend Object แล้วใช้เมธอด set_linewidth() หรือปรับผ่าน get_frame()
วิธีที่ 1: ใช้ get_frame().set_linewidth() (แนะนำ)
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, 'r-', linewidth=3, label='y = sin(x)')
# สร้าง Legend และปรับขอบ
legend = ax.legend(loc='upper right', fontsize=12, framealpha=0.9)
# ปรับความหนาขอบ (Line Width ของ Frame)
legend.get_frame().set_linewidth(3.0) # ความหนาขอบ (Default = 1.0)
legend.get_frame().set_edgecolor('darkred') # สีขอบ
legend.get_frame().set_facecolor('lightyellow') # สีพื้นหลัง
legend.get_frame().set_boxstyle('round,pad=0.5') # มุมโค้ง
ax.set_title('Custom Legend Frame Style', fontsize=14)
ax.grid(True, alpha=0.3)
plt.show()
วิธีที่ 2: ปรับผ่าน rcParams (Global)
import matplotlib.pyplot as plt # ตั้งค่า Global สำหรับ Legend ทุกตัว plt.rcParams['legend.framealpha'] = 0.9 plt.rcParams['legend.edgecolor'] = 'black' plt.rcParams['legend.linewidth'] = 2.0 # ความหนาขอบ plt.rcParams['legend.fancybox'] = True # มุมโค้ง plt.rcParams['legend.frameon'] = True # แสดงกรอบ # ทดสอบ import numpy as np x = np.linspace(0, 10, 50) plt.plot(x, np.sin(x), label='sin(x)') plt.plot(x, np.cos(x), label='cos(x)') plt.legend() plt.show()
วิธีที่ 3: ปรับ LineWidth ของ Legend Handles (Marker/Line ใน Legend)
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
fig, ax = plt.subplots()
line1, = ax.plot(x, np.sin(x), 'r-', linewidth=2, label='sin(x)')
line2, = ax.plot(x, np.cos(x), 'b--', linewidth=2, label='cos(x)')
legend = ax.legend(fontsize=12)
# ปรับ Line Width ของ Legend Handles (ไม่ใช่ Frame)
for handle in legend.legend_handles:
handle.set_linewidth(6) # ทำให้เส้นใน Legend หนาขึ้น
ax.set_title('Legend Handles Line Width = 6', fontsize=14)
ax.grid(True, alpha=0.3)
plt.show()
ผลลัพธ์
Legend มีกรอบขอบหนา 3 พิกเซล สีขอบสีแดงเข้ม พื้นหลังสีเหลืองอ่อน มุมโค้งมน
สรุปคุณสมบัติ Frame ที่ปรับได้
| เมธอด/คุณสมบัติ | คำอธิบาย |
|---|---|
get_frame().set_linewidth(w) | ความหนาขอบกรอบ |
get_frame().set_edgecolor(c) | สีขอบกรอบ |
get_frame().set_facecolor(c) | สีพื้นหลังกรอบ |
get_frame().set_alpha(a) | ความโปร่งใส (0-1) |
get_frame().set_boxstyle('round,pad=0.5') | รูปทรงกรอบ (round, square, sawtooth) |
get_frame().set_linestyle('--') | รูปแบบเส้นขอบ |