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

วิธีแสดงเฉพาะข้อความใน Legend โดยไม่มีสัญลักษณ์ใน Matplotlib

ใช้ ax.legend() ตั้งค่า handlelength=0, handletextpad=0, fancybox=True เพื่อซ่อนสัญลักษณ์เส้น/เครื่องหมาย ทิ้งแค่ข้อความป้ายกำกับ

ขั้นตอนการทำงาน

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้างข้อมูลและพลอตพร้อม label
  3. สร้าง legend ด้วย ax.legend(handlelength=0, handletextpad=0, fancybox=True)
  4. แสดงผล

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

import numpy as np
from matplotlib import pyplot as plt

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

x = np.random.rand(100)
y = np.random.rand(100)

fig, ax = plt.subplots()
ax.plot(x, y, label='Zig-Zag', c="red")
ax.legend(loc="upper right", handlelength=0, handletextpad=0, fancybox=True)
plt.show()

ผลลัพธ์

วิธีแสดงเฉพาะข้อความใน Legend โดยไม่มีสัญลักษณ์ใน Matplotlib