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

วิธีเพิ่ม Legend บน Seaborn FacetGrid Bar Plot ด้วย Matplotlib

การเพิ่ม Legend ให้ FacetGrid Bar Plot

ใช้ g.add_legend() หลังจาก map_dataframe เพื่อแสดง legend อัตโนมัติ

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้าง DataFrame พร้อมคอลัมน์ col1
  • สร้าง FacetGrid ด้วย col และ hue
  • ใช้ map_dataframe() พร้อม sns.scatterplot
  • ตั้งค่า axis labels
  • เพิ่ม legend ด้วย g.add_legend()
  • แสดงผลด้วย show()

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

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

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

df = pd.DataFrame({'col1': [3, 7, 8]})
g = sns.FacetGrid(df, col="col1", hue="col1")
g.map_dataframe(sns.scatterplot)
g.set_axis_labels("X", "Y")
g.add_legend()
plt.show()

คำอธิบาย

FacetGrid สร้าง subplots แยกตามค่า col hue ใช้สีแยกกลุ่ม add_legend() รวบรวม legend จากทุก axes