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

การพล็อต Histogram สองชุดติดกัน ด้วย Matplotlib

ใช้ plt.subplots(1, 2) สร้าง Subplots 1 แถว 2 คอลัมน์ แล้ว Plot Histogram แต่ละชุดใน Axes แยกกัน

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง DataFrame 2 ชุด (df1, df2)
  3. สร้าง Subplots 1x2
  4. Plot Histogram แต่ละชุดใน Axes ต่างกัน
  5. แสดงผล

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


from matplotlib import pyplot as plt
import pandas as pd

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

df1 = pd.DataFrame(dict(a=[1, 1, 1, 1, 3]))
df2 = pd.DataFrame(dict(b=[1, 1, 2, 1, 3]))

fig, axes = plt.subplots(1, 2)

df1.hist('a', ax=axes[0])
df2.hist('b', ax=axes[1])

plt.show()

การใช้ Matplotlib โดยตรง (ไม่ใช้ Pandas)


fig, axes = plt.subplots(1, 2)

data1 = [1, 1, 1, 1, 3]
data2 = [1, 1, 2, 1, 3]

axes[0].hist(data1, bins=5, alpha=0.7, color='blue', edgecolor='black')
axes[1].hist(data2, bins=5, alpha=0.7, color='red', edgecolor='black')

axes[0].set_title('Dataset A')
axes[1].set_title('Dataset B')

plt.show()

การเปรียบเทียบในกราฟเดียว (Overlaid)


plt.hist(data1, bins=5, alpha=0.5, label='Data 1', color='blue')
plt.hist(data2, bins=5, alpha=0.5, label='Data 2', color='red')
plt.legend()
plt.show()

ผลลัพธ์

Figure แสดง 2 Histogram ติดกัน ซ้าย: ข้อมูล A (ส่วนใหญ่ค่า 1) ขวา: ข้อมูล B (กระจาย 1,2,3)