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

วิธาตั้งชื่อเส้นกราฟหลายเส้นใน Legend เดียวกันใน Matplotlib

การตั้งชื่อ (Label) ให้เส้นกราฟหลายเส้นเพื่อแสดงใน Legend เดียวกัน ใน Matplotlib ทำได้โดยระบุพารามิเตอร์ label ในเมธอด plot() แล้วเรียก legend()

วิธีพื้นฐาน

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()

# Plot เส้นแรก พร้อม Label
ax.plot(x, np.sin(x), 'b-', linewidth=2, label='Sine Wave')

# Plot เส้นที่สอง พร้อม Label
ax.plot(x, np.cos(x), 'r--', linewidth=2, label='Cosine Wave')

# Plot เส้นที่สาม พร้อม Label
ax.plot(x, np.sin(x) * np.cos(x), 'g:', linewidth=2, label='Sin × Cos')

# แสดง Legend
ax.legend(loc='upper right', fontsize=12, framealpha=0.9)

ax.set_xlabel('X', fontsize=12)
ax.set_ylabel('Y', fontsize=12)
ax.set_title('Multiple Lines with Legend Labels', fontsize=14)
ax.grid(True, alpha=0.3)

plt.show()

วิธีขั้นสูง: ควบคุม Legend ให้ละเอียด

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(0, 10, 100)
fig, ax = plt.subplots()

# Plot หลายเส้น
lines = []
lines.append(ax.plot(x, np.sin(x), 'b-', linewidth=2)[0])
lines.append(ax.plot(x, np.cos(x), 'r--', linewidth=2)[0])
lines.append(ax.plot(x, np.sin(x)*0.5, 'g:', linewidth=2)[0])

# Labels แยกต่างหาก
labels = ['Sine (sin x)', 'Cosine (cos x)', 'Half Amplitude (0.5 sin x)']

# สร้าง Legend แบบ Manual
legend = ax.legend(lines, labels, 
                   loc='upper right',
                   fontsize=11,
                   framealpha=0.9,
                   fancybox=True,
                   shadow=True,
                   ncol=1,           # จำนวนคอลัมน์
                   columnspacing=1.5,
                   handlelength=2.5, # ความยาว Handle
                   handletextpad=0.8,# ระยะ Handle-Text
                   borderpad=1.0,    # Padding ขอบ
                   title='Functions', title_fontsize=12)

# ปรับสีขอบ Legend
legend.get_frame().set_edgecolor('gray')
legend.get_frame().set_linewidth(1.5)

ax.set_title('Advanced Legend Customization', fontsize=14)
ax.grid(True, alpha=0.3)

plt.show()

ตัวอย่าง: Legend สำหรับ Subplots หลายอัน (Shared Legend)

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 2, figsize=(12, 8), sharex=True, sharey=True)
x = np.linspace(0, 10, 100)

titles = ['sin(x)', 'cos(x)', 'sin(2x)', 'cos(2x)']
funcs = [np.sin, np.cos, lambda x: np.sin(2*x), lambda x: np.cos(2*x)]
colors = ['blue', 'red', 'green', 'purple']

all_lines = []
all_labels = []

for ax, title, func, color in zip(axes.flat, titles, funcs, colors):
    line, = ax.plot(x, func(x), color=color, linewidth=2, label=title)
    ax.set_title(title, fontsize=11)
    ax.grid(True, alpha=0.3)
    all_lines.append(line)
    all_labels.append(title)

# Legend ร่วมกันด้านนอก
fig.legend(all_lines, all_labels, 
           loc='lower center', ncol=4, fontsize=11,
           bbox_to_anchor=(0.5, 0.02), framealpha=0.9)

fig.suptitle('Shared Legend for Multiple Subplots', fontsize=16)
plt.tight_layout()
plt.subplots_adjust(bottom=0.15)
plt.show()

ผลลัพธ์

กราฟแสดงหลายเส้นพร้อม Legend ที่มีชื่อชัดเจน สีตรงกับเส้น รองรับการปรับแต่งรูปแบบ Legend ให้สวยงาม

คำแนะนำ

  • ระบุ label ใน plot() ทุกครั้ง แล้วแค่เรียก ax.legend()
  • ใช้ label='_nolegend_' เพื่อซ่อนเส้นที่ไม่ต้องการใน Legend
  • ax.legend() คืนค่า Legend Object สามารถปรับแต่งต่อได้ (get_frame(), get_texts())
  • สำหรับ Subplots หลายอัน ใช้ fig.legend() ร่วม bbox_to_anchor