การทำให้ Axes (พื้นที่วาดกราฟ) ใสหรือโปร่งแสง ใน Matplotlib ทำได้โดยตั้งค่า Alpha (Transparency) ของ Patch (พื้นหลัง Axes) ด้วย set_alpha()
วิธีการ
- สร้าง Figure และ Axes
- เข้าถึง Patch ของ Axes ผ่าน
ax.patch - ใช้
ax.patch.set_alpha(0.0)(ใสเต็มที่) หรือค่าระหว่าง 0-1 - หากมีหลาย Axes ให้ตั้งค่าแต่ละอัน
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
# ตั้งค่าพื้นหลัง Figure (Optional)
fig.patch.set_facecolor('lightgray')
# ตั้งค่าพื้นหลัง Axes ให้ใส (Transparent)
ax.patch.set_alpha(0.0) # 0 = ใสเต็มที่, 1 = ทึบเต็มที่
# วาดกราฟตัวอย่าง
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y, 'b-', linewidth=2.5, label='sin(x)')
ax.fill_between(x, y, alpha=0.3, color='blue')
# เพิ่ม Grid และ Legend
ax.grid(True, alpha=0.3)
ax.legend(fontsize=12, framealpha=0.5) # Legend ก็ทำให้ใสได้
ax.set_title('Transparent Axes Background (alpha=0.0)', fontsize=14)
plt.show()
ตัวอย่างขั้นสูง: Overlay 2 Axes (Axes บน Axes)
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
# Axes ที่ 1: พื้นหลังสีส้ม
ax1 = fig.add_subplot(111)
ax1.set_facecolor('orange')
ax1.plot([0, 1, 2, 3], [0, 1, 0, 1], 'r-', linewidth=3, label='Axes 1 (Bottom)')
ax1.set_ylim(-0.5, 1.5)
# Axes ที่ 2: ใส (Transparent) วางทับ Axes 1
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # [left, bottom, width, height] ใน Figure Coords
ax2.patch.set_alpha(0.0) # ใสเต็มที่
t = np.linspace(0, 3, 100)
s = np.sin(2 * np.pi * t)
ax2.plot(t, s, 'b-', linewidth=2, label='Axes 2 (Top, Transparent)')
ax2.set_ylim(-1.5, 1.5)
ax2.set_facecolor('none') # ทางเลือกอื่น: 'none'
# ซ่อน Ticks ของ Axes บน (ถ้าต้องการ)
ax2.tick_params(labelbottom=False, labelleft=False)
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()
ผลลัพธ์
Axes บนสุด (ax2) ใส ทำให้มองเห็น Axes ล่าง (ax1) และกราฟทั้งสองชุดทับซ้อนกันได้
คุณสมบัติ Patch ที่เกี่ยวข้อง
| คุณสมบัติ | คำอธิบาย |
|---|---|
ax.patch.set_alpha(alpha) | ความโปร่งใส 0.0-1.0 |
ax.patch.set_facecolor(color) | สีพื้นหลัง ('none' = ใส) |
ax.patch.set_edgecolor(color) | สีขอบ Axes |
ax.patch.set_linewidth(w) | ความหนาขอบ Axes |
fig.patch.set_alpha(alpha) | ความโปร่งใสของ Figure Background |
การบันทึกภาพพร้อมพื้นหลังใส
# บันทึก PNG พร้อม Transparency
plt.savefig('transparent_plot.png',
transparent=True, # สำคัญ: ทำให้ Figure Background ใส
dpi=300,
bbox_inches='tight',
facecolor='auto', # ใช้ Facecolor ของ Figure
edgecolor='none')
# บันทึก SVG (Vector, ใสโดยค่าเริ่มต้น)
plt.savefig('transparent_plot.svg', transparent=True)
คำแนะนำ
ax.patch.set_alpha(0.0)ทำให้พื้นที่ Plot ใส แต่ Grid, Ticks, Labels ยังมองเห็นได้- ใช้
ax.set_facecolor('none')ทางเลือกอื่นที่เทียบเท่า - สำหรับ Overlay Axes ใช้
fig.add_axes([left, bottom, width, height])แทน subplot - บันทึกด้วย
transparent=Trueใน savefig เพื่อให้ไฟล์ PNG ใสจริง