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

วิธีเพิ่ม Shared X-label และ Y-label ให้ Plot จาก Pandas Plot

การเพิ่ม Shared Axis Labels ใน Pandas Subplots

ใช้ df.plot() พร้อม subplots=True, sharex=True, sharey=True

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้าง DataFrame 4 คอลัมน์ 4 แถว
  • พล็อตด้วย kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True
  • แสดงผลด้วย show()

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

import pandas as pd
import matplotlib.pyplot as plt

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

df = pd.DataFrame(
    {'First': [0.3, 0.2, 0.5, 0.2], 'Second': [0.1, 0.0, 0.3, 0.1],
     'Third': [0.2, 0.5, 0.0, 0.7], 'Fourth': [0.6, 0.3, 0.4, 0.6]},
    index=list('1234')
)

axes = df.plot(kind="bar", subplots=True, layout=(2, 2),
               sharey=True, sharex=True)
plt.show()

คำอธิบาย

  • sharex=True: แกน x ใช้ scale เดียวกัน ทุก subplot
  • sharey=True: แกน y ใช้ scale เดียวกัน ทุก subplot
  • layout=(2,2): จัดเรียง 2 แถว 2 คอลัมน์