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

วิธีสร้างฮิสโตแกรมแบบ Log Scale ใน Python

การสร้างฮิสโตแกรมที่แกน Y เป็นมาตราส่วนลอการิทึม (Log Scale) ใน Matplotlib ทำได้โดยตั้งค่า log=True ในฟังก์ชัน plt.hist() เหมาะสำหรับข้อมูลที่มีช่วงค่ากว้างมาก หรือมี Outliers

ขั้นตอนการทำงาน

  1. นำเข้า numpy และ matplotlib.pyplot
  2. เตรียมข้อมูล (ตัวอย่างใช้ np.array([5, 5, 5, 5]))
  3. พลอตฮิสโตแกรมด้วย plt.hist() พร้อมพารามิเตอร์:
    • density=True - ปรับมาตรฐานพื้นที่ = 1
    • log=True - แกน Y แบบ Log scale
  4. แสดงผลด้วย plt.show()

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

import numpy as np
import matplotlib.pyplot as plt

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

k = np.array([5, 5, 5, 5])
x, bins, patches = plt.hist(np.log(k), density=True, log=True)
plt.show()

หมายเหตุสำคัญ

  • ตัวอย่างใช้ np.log(k) ก่อนพลอต ทำให้ข้อมูลกลายเป็นค่าลอการิทึมก่อน
  • หากต้องการแกน Y แบบ Log แต่ข้อมูลยังคงเป็นค่าเดิม ใช้ plt.yscale('log') แทน
  • log=True ใน hist() ทำงานกับความถี่ (counts) ไม่ใช่ค่าข้อมูลดิบ

วิธีแนะนำ: ใช้ plt.yscale('log')


import numpy as np
import matplotlib.pyplot as plt

data = np.random.exponential(scale=2, size=10000)

plt.hist(data, bins=50, density=True, alpha=0.7, edgecolor='black')
plt.yscale('log')
plt.xlabel('Value')
plt.ylabel('Density (log scale)')
plt.title('Exponential Distribution - Log Scale Y-axis')
plt.grid(True, which='both', linestyle='--', alpha=0.5)
plt.show()

เมื่อควรใช้ Log Scale

  • ข้อมูลกระจายแบบ Power Law หรือ Exponential
  • มีค่าความถี่ต่างกันหลายออเดอร์ (orders of magnitude)
  • ต้องการเห็นรายละเอียดของค่าที่น้อย/หายาก
  • Financial data, Network degree distribution, Word frequency

การประยุกต์ใช้

เหมาะสำหรับการวิเคราะห์การกระจายของข้อมูลที่มี Eccentric distribution การตรวจสอบ Power Law behavior หรือการแสดงข้อมูลทางการเงิน/เครือข่าย