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

วิธีคืนค่า matplotlib.figure.Figure Object จาก Pandas Plot Function

การเข้าถึง Figure Object จาก Pandas Plot

ใช้ ax.get_figure() บน Axes object ที่คืนจาก pandas plot

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้าง DataFrame df
  • พล็อต horizontal bar chart ด้วย df.plot.barh() ได้ Axes object
  • ดึง Figure ด้วย ax.get_figure()
  • เพิ่ม legend และแสดงผล

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

from matplotlib import pyplot as plt
import pandas as pd

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

df = pd.DataFrame({'a': range(10)})
ax = df.plot.barh(color=(1, 0, 0, 0.25))
fig = ax.get_figure()
ax.legend(loc='lower right')
plt.show()

คำอธิบาย

df.plot.barh() คืนค่า Axes object ใช้ .get_figure() ได้ Figure object