Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Seaborn hiển thị Histogram trong Python

Trực quan hóa dữ liệu quan trọng vì giúp hiểu dữ liệu mà không nhìn con số, tính toán phức tạp. Giúp truyền đạt thông tin định lượng hiệu quả. Seaborn giúp trực quan hóa dữ liệu với theme tùy chỉnh và giao diện cấp cao.

Hãy xem ví dụ hiển thị Histogram:

Ví dụ

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt

df = sb.load_dataset('iris')
sb.distplot(df['petal_length'], kde=False)
plt.show()

Đầu ra

Cách dùng Seaborn hiển thị Histogram trong Python

Giải thích

  • Nhập các gói thư viện cần thiết.
  • Dữ liệu đầu vào 'iris_data' tải từ scikit-learn.
  • Dùng load_dataset tải dữ liệu iris.
  • Trực quan hóa bằng distplot.
  • Tham số kde đặt False vì chỉ muốn hiển thị histogram.
  • Dữ liệu trực quan hiển thị trên console.

Cập nhật quan trọng: distplot đã deprecated từ Seaborn 0.11+. Nên dùng histplot hoặc displot:

# Cách mới (khuyến khích)
sb.histplot(data=df, x='petal_length')
# hoặc
sb.displot(data=df, x='petal_length', kind='hist')

histplot cho phép tùy chỉnh: bins (số bin), kde=True (vẽ thêm đường KDE), stat='density' (mật độ thay vì count).