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

วิธีสร้าง Histogram ที่มี Bins แบบ Logarithmic ใน Python


เราสามารถตั้งค่า bins แบบ Logarithmic ขณะวาด Histogram ด้วย plt.hist(bins=...)

ขั้นตอน

  • สร้างอาเรย์ x โดย range คือ 100

  • วาด Histogram ด้วย plt.hist() สามารถส่ง logarithmic bins ผ่าน np.logspace ที่คืนค่าตัวเลขที่กระจายตัวเท่าๆ กันบนมาตราส่วนลอการิทึม

  • ดึง Axes ปัจจุบัน สร้างใหม่หากจำเป็น และตั้งค่ามาตราส่วนแกน X

  • ใช้ plt.show() เพื่อแสดงกราฟ

ตัวอย่าง

from matplotlib import pyplot as plt
import numpy as np
x = np.array(range(100))
plt.hist(x, bins=np.logspace(start=np.log10(10), stop=np.log10(15), num=10))
plt.gca().set_xscale("log")
plt.show()

ผลลัพธ์

วิธีสร้าง Histogram ที่มี Bins แบบ Logarithmic ใน Python