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

Python Matplotlib: เปลี่ยนสีพื้นหลังกราฟ (Face Color)

บทนำ

การเปลี่ยนสีพื้นหลังของพื้นที่วาดกราฟ (axes face color) ใน Matplotlib ใช้เมธอด ax.set_facecolor() สีพื้นหลังของ figure ใช้ fig.set_facecolor()

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


import numpy as np
import matplotlib.pyplot as plt

# กำหนดขนาดรูป
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# สร้างข้อมูล
x = np.linspace(-10, 10, 100)
y = np.sin(x)

# สร้าง figure และ axes
fig, ax = plt.subplots()

# วาดกราฟ
ax.plot(x, y, color='yellow', linewidth=7)

# เปลี่ยนสีพื้นหลัง axes
ax.set_facecolor('red')

# เปลี่ยนสีพื้นหลัง figure (optional)
fig.set_facecolor('lightgray')

plt.show()

ผลลัพธ์

กราฟ sine wave สีเหลืองบนพื้นหลังสีแดง (axes) และสีเทาอ่อน (figure)

รูปแบบสีที่รองรับ

รูปแบบตัวอย่าง
Named color'red', 'blue', 'green', 'yellow', 'black', 'white'
Hex'#FF0000', '#00FF00', '#1f77b4'
RGB tuple(1, 0, 0), (0.5, 0.5, 0.5)
RGBA tuple(1, 0, 0, 0.5) - alpha=0.5
Grayscale string'0.5' (50% gray)

การตั้งค่าสีหลายแบบ


fig, ax = plt.subplots()

# 1. Axes face color (พื้นที่วาดกราฟ)
ax.set_facecolor('#f0f0f0')

# 2. Figure face color (พื้นที่รอบนอก)
fig.set_facecolor('white')

# 3. ผ่าน rcParams (global)
plt.rcParams['axes.facecolor'] = '#f5f5f5'
plt.rcParams['figure.facecolor'] = 'white'

# 4. ตั้งค่าพร้อมกันใน subplots
fig, ax = plt.subplots(facecolor='lightblue')
ax.set_facecolor('white')

กรณีใช้งานจริง

  • Dark theme: ax.set_facecolor('#1e1e1e'), fig.set_facecolor('#121212')
  • Highlight พื้นที่เฉพาะ: ใช้ ax.axvspan() หรือ ax.axhspan()
  • Print-friendly: ใช้สีขาว/สีอ่อน

สรุป

  • ax.set_facecolor(color): เปลี่ยนสีพื้นหลัง axes (พื้นที่กราฟ)
  • fig.set_facecolor(color): เปลี่ยนสีพื้นหลัง figure (ทั้งหน้าต่าง)
  • ใช้ร่วมกับ ax.grid() สี grid ควรคอนทราสต์กับพื้นหลัง