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

วิธีวาง Legend นอกกราฟด้วย Pandas (Matplotlib)


ขั้นตอนการวาง Legend นอกกราฟด้วย Pandas

  • สร้าง Dictionary d มี Key Column1 และ Column2
  • สร้าง DataFrame ด้วย DataFrame(d)
  • พล็อต DataFrame พร้อม List ของ Styles
  • ใช้ legend() วาง Legend บน Figure พารามิเตอร์ bbox_to_anchor ให้การควบคุมตำแหน่ง Legend ได้ละเอียด
  • ใช้เมธอด show() แสดง Figure

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

import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {'Column 1': [i for i in range(10)], 'Column 2': [i * i for i in range(10)]}
df = pd.DataFrame(d)
df.plot(style=['o', 'rx'])
plt.legend(bbox_to_anchor=(1.0, 1.0))
plt.show()

ผลลัพธ์

วิธีวาง Legend นอกกราฟด้วย Pandas (Matplotlib)