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

การดึงข้อมูล bins จากฟังก์ชัน histogram ใน Matplotlib


รับข้อมูล bins และความถี่จาก histogram

ใช้ numpy.histogram() คำนวณ histogram แล้วนำมาวาด bar chart เอง

ขั้นตอน

  1. สร้าง list ตัวเลขสำหรับ data และ bins
  2. คำนวณ histogram ด้วย histogram()
  3. ดึง hist และ edges จากผลลัพธ์
  4. คำนวณความถี่ (frequency)
  5. วาด bar chart ด้วย bins และ freq
  6. แสดงด้วย show()

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

import numpy as np
from matplotlib import pyplot as plt

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

a = [-0.125, .15, 8.75, 72.5, -44.245, 88.45]
bins = np.arange(-180, 181, 20)
hist, edges = np.histogram(a, bins)
freq = hist/float(hist.sum())
plt.bar(bins[:-1], freq, width=20, align="edge", ec="k", color='red')
plt.show()

ผลลัพธ์

การดึงข้อมูล bins จากฟังก์ชัน histogram ใน Matplotlib