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

วิธีปิดการแสดง Scientific Notation บนแกน Y ใน Seaborn/Matplotlib

เมื่อค่าบนแกน Y ใหญ่มากหรือเล็กมาก Matplotlib จะแสดงเป็น Scientific Notation (เช่น 1e6, 5e-3) ซึ่งอ่านยาก สามารถปิดได้ด้วย ticklabel_format(style='plain') หรือใช้ ScalarFormatter

วิธีที่ 1: ใช้ ticklabel_format() (ง่ายที่สุด)

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# ข้อมูลตัวอย่าง: ค่าใหญ่
df = pd.DataFrame({
    "Category": ["A", "B", "C", "D", "E"],
    "Value": [1500000, 2300000, 1800000, 3100000, 900000]  # 1.5M, 2.3M, etc.
})

# สร้าง Bar Plot ด้วย Seaborn
ax = sns.barplot(data=df, x="Category", y="Value", palette="viridis")

# ปิด Scientific Notation บนแกน Y
plt.ticklabel_format(style='plain', axis='y')  # สำคัญ!

ax.set_title('Bar Plot with Plain Y-Axis Labels', fontsize=14)
ax.set_ylabel('Value (Plain Format)', fontsize=12)
plt.show()

วิธีที่ 2: ใช้ ScalarFormatter (ควบคุมได้ละเอียด)

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import seaborn as sns
import pandas as pd
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame({
    "Category": ["A", "B", "C", "D", "E"],
    "Value": [1500000, 2300000, 1800000, 3100000, 900000]
})

ax = sns.barplot(data=df, x="Category", y="Value", palette="viridis")

# ใช้ ScalarFormatter
formatter = ScalarFormatter(useOffset=False, useMathText=False)
formatter.set_scientific(False)  # ปิด Scientific Notation
ax.yaxis.set_major_formatter(formatter)

# เพิ่ม Comma Separator (Optional)
from matplotlib.ticker import FuncFormatter
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: f'{int(x):,}'))

ax.set_title('Y-Axis with Comma Separators', fontsize=14)
plt.show()

วิธีที่ 3: ใช้ EngFormatter (Engineering Notation: 1k, 1M, 1G)

from matplotlib.ticker import EngFormatter

ax.yaxis.set_major_formatter(EngFormatter(unit='', places=1))
# แสดงเป็น 1.5M, 2.3M, 1.8M, 3.1M, 900k

ผลลัพธ์

แกน Y แสดงตัวเลขเต็ม (1500000, 2300000, ...) หรือพร้อม Comma (1,500,000) แทน Scientific Notation

สรุป Formatter ทั้งหมด

Formatterรูปแบบผลลัพธ์เหมาะสำหรับ
ScalarFormatter(useOffset=False)1500000ทั่วไป ปิด Scientific
FuncFormatter(lambda x,_: f'{x:,.0f}')1,500,000อ่านง่าย ตัวเลขใหญ่
EngFormatter(unit='', places=1)1.5M, 900kEngineering/Scientific
StrMethodFormatter('{x:,.0f}')1,500,000Format แบบ Python String

⚠️ ข้อควรระวัง

  • ticklabel_format() ทำงานเฉพาะกับ ScalarFormatter (Default) หากใช้ Formatter อื่นจะไม่มีผล
  • Seaborn 的 factorplot เปลี่ยนชื่อเป็น catplot แล้ว (Deprecated)
  • หากใช้ ax.set_yscale('log') จะใช้ LogFormatter แทน
  • ใช้ axis='y' หรือ axis='x' หรือ axis='both' ใน ticklabel_format

การตั้งค่า Global (rcParams)

import matplotlib.pyplot as plt

# ปิด Scientific Notation ทั่วทั้งโปรแกรม
plt.rcParams['axes.formatter.useoffset'] = False
plt.rcParams['axes.formatter.use_scientific'] = False
# หรือ
plt.rcParams['axes.formatter.limits'] = (-3, 6)  # ใช้ Scientific เฉพาะนอกช่วง 10^-3 ถึง 10^6