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

วิธีทำให้ Marker สองตัวใช้ Label เดียวกันใน Legend ของ Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูล x และ y ด้วย numpy
  • พล็อต x และ y (เป็น sin(x) และ cos(x)) ด้วย plot()
  • วาง legend ด้วย location=1
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import numpy as np
import matplotlib.pyplot as plt

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

x = np.linspace(-5, 5, 100)
plt.plot(x, np.sin(x), ls="dotted", label='y=f(x)')
plt.plot(x, np.cos(x), ls="-", label='y=f(x)')
plt.legend(loc=1)
plt.show()

ผลลัพธ์

วิธีทำให้ Marker สองตัวใช้ Label เดียวกันใน Legend ของ Matplotlib

ไม่แนะนำให้ Marker สองตัวใช้ Label เดียวกัน เพราะกราฟต่างควรจะมี Marker และ Label ต่างกัน