Trong kỷ nguyên dữ liệu lớn (Big Data) và trí tuệ nhân tạo (AI) bùng nổ như năm 2026, khả năng “đọc hiểu” dữ liệu thô để biến chúng thành insight (sự thấu hiểu) hành động là kỹ năng cốt lõi không chỉ của Data Scientist mà cả của Analyst, Product Manager, Marketing và cả C-level. Và công cụ đắt giá nhất trong hộp công cụ khám phá dữ liệu 탐索 (Exploratory Data Analysis – EDA) chính là biểu đồ phân phối của biến (Distribution Plot).

Khác với các bài viết chỉ liệt kê định nghĩa khô khan, bài viết này sẽ đi sâu vào tư duy thống kê, lựa chọn biểu đồ phù hợp cho từng loại dữ liệu, cách giải thích kết quả chuyên nghiệp, và demo code thực chiến với Python (Pandas, Seaborn, Matplotlib, Plotly) cập nhật nhất cho môi trường làm việc năm 2026. Chúng ta sẽ cùng nhau giải mã “chuyện gì đang xảy ra sau những cột histogram và đường cong mật độ”.

Phần 1: Nền Tảng Lý Thuyết – Tại Sao Phân Phối Lại Quan Trọng Đến Như Vậy?

Trước khi vẽ biểu đồ, chúng ta phải hiểu bản chất của “biến” (Variable) và “phân phối” (Distribution).

1.1. Phân loại biến: Chìa khóa chọn biểu đồ

Không phải biểu đồ nào cũng vẽ cho mọi loại dữ liệu. Năm 2026, với sự đa dạng của dữ liệu phi cấu trúc (unstructured data) được cấu trúc hóa, việc phân loại đúng chuẩn là bắt buộc:

  • Biến định lượng (Quantitative/Numerical): Có thể đo lường, tính toán.
    • Rời rạc (Discrete): Số lượng khách hàng, số lượng sản phẩm bán ra, số lần click (chỉ lấy giá trị nguyên).
    • Liên tục (Continuous): Doanh thu, chiều cao, cân nặng, nhiệt độ, thời gian phản hồi API, latency (lấy mọi giá trị trong một khoảng).
  • Biến định tính (Qualitative/Categorical): Mô tả đặc tính, chất lượng.
    • Thứ tự (Ordinal): Mức độ hài lòng (Rất tệ -> Rất hài lòng), cấp bậc công việc (Fresher -> Principal).
    • Danh mục (Nominal): Quốc gia, màu sắc, thiết bị (Mobile/Desktop), mã(zip code – tuy là số nhưng bản chất là danh mục).

Quy tắc vàng 2026: Luôn kiểm tra dtype trong Pandas (df.dtypes) và quan trọng hơn là kiểm tra nunique() (số giá trị duy nhất) trước khi quyết định vẽ biểu đồ gì. Một cột int64 có thể là Categorical (ví dụ: user_id, product_category_id).

1.2. Phân phối xác suất: “Bản đồ” của biến ngẫu nhiên

Phân phối của biến cho ta biết: Giá trị nào xuất hiện với tần suất/khả năng bao nhiêu?

  • PMF (Probability Mass Function): Dành cho biến rời rạc. Tổng xác suất = 1.
  • PDF (Probability Density Function): Dành cho biến liên tục. Diện tích dưới đường cong = 1. Lưu ý: Giá trị trục tung (density) có thể > 1, nhưng diện tích thì không.
  • CDF (Cumulative Distribution Function): $F(x) = P(X \le x)$. Rất hữu ích để xem percentiles (phân vị), so sánh phân phối, hoặc thiết lập ngưỡng (threshold) cho anomaly detection.

1.3. Các đặc trưng hình dạng phân phối (Shape Characteristics)

Khi nhìn vào biểu đồ phân phối năm 2026, các chuyên gia dữ liệu tìm 4 đặc trưng chính (Moment statistics):

Biểu Đồ Phân Phối Của Biến
Biểu Đồ Phân Phối Của Biến
  1. Trung tâm (Central Tendency): Mean (Trung bình), Median (Trung vị), Mode (Mốt). Mean nhạy cảm outlier, Median robust.
  2. Độ tán (Spread/Variability): Std (Độ lệch chuẩn), Variance (Phương sai), IQR (Khoảng tứ phân vị), Range. IQR robust hơn Std.
  3. Độ lệch (Skewness):
    • Right-skewed (Lệch phải/Dương): Đuôi kéo dài bên phải (Mean > Median). Ví dụ: Thu nhập, giá nhà, thời gian chờ.
    • Left-skewed (Lệch trái/Âm): Đuôi kéo dài bên trái (Mean < Median). Ví dụ: Điểm thi dễ, tuổi thọ.
    • Symmetric (Đối xứng): Mean ≈ Median ≈ Mode. Ví dụ: Chiều cao, lỗi đo lường (thường近似 Normal).
  4. Độ nhọn (Kurtosis):
    • Leptokurtic (Nhọn): Đỉnh cao, đuôi dày (Outlier nhiều). Kurtosis > 3 (Excess > 0).
    • Platykurtic (Bẹp): Đỉnh thấp, đuôi mỏng (Outlier ít). Kurtosis < 3 (Excess < 0).
    • Mesokurtic (Bình thường): Gần Normal. Kurtosis ≈ 3 (Excess ≈ 0).

Insight 2026: Trong ML Ops hiện nay, việc monitor Skewness và Kurtosis của các feature input (data drift detection) quan trọng không kém monitor Accuracy của model. Nếu phân phối feature thay đổi đột ngột (ví dụ Skewness từ 0.5 nhảy lên 5.0), model có thể đang.predict sai lệch mà không báo lỗi.

Phần 2: “Bộ Sưu Tập” Biểu Đồ Phân Phối – Chọn Cái Nào, Khi Nào, Và Tại Sao?

Đây là phần cốt lõi. Chúng ta sẽ phân tích 5 nhóm biểu đồ chính, từ cơ bản đến nâng cao, kèm theo Best Practices năm 2026 (Accessibility, Interactivity, Storytelling).

2.1. Histogram (Biểu đồ tần suất) – “Người bạn cũ đáng tin cậy”

  • Dành cho: Biến liên tục (Continuous) hoặc Rời rạc với nhiều giá trị.
  • Nguyên lý: Chia dữ liệu thành các “bin” (ngăn/bucket), đếm số lượng quan sát trong mỗi bin. Trục tung: Count (Số lượng) hoặc Density (Mật độ).
  • Vấn đề kinh điển: Chọn số lượng bin (Number of Bins).
    • Quá ít bin -> Mất chi tiết, che giấu mode (multimodal).
    • Quá nhiều bin -> Nhiễu (noisy), khó nhìn hình dạng chung.
  • Quy tắc chọn Bin năm 2026 (Tự động hóa):
    • Sturges: $k = \lceil \log_2 n \rceil + 1$ (Cũ, chỉ tốt cho dữ liệu gần Normal, size nhỏ).
    • Freedman-Diaconis (Khuyên dùng cho dữ liệu thực tế có outlier): $Bin Width = 2 \frac{IQR}{n^{1/3}}$. Robust với outlier.
    • Scott’s Rule: $Bin Width = \frac{3.5 \sigma}{n^{1/3}}$ (Giả định Normal).
    • Auto (Matplotlib/Seaborn default): Thường dùng Maximum of Sturges and Freedman-Diaconis hoặc thuật toán Knuth (Bayesian) / Blocks (Astropy).

💡 Pro Tip 2026: Luôn vẽ Histogram với stat="density" (mật độ) thay vì count nếu bạn muốn so sánh với đường PDF lý thuyết (Normal, Log-normal…) hoặc so sánh 2 nhóm có kích thước mẫu khác nhau.

2.2. KDE Plot (Kernel Density Estimation) – “Đường cong mượt mà”

  • Dành cho: Biến liên tục. Ưu tiên khi muốn nhìn hình dạng phân phối cơ bản (smooth shape) thay vì chi tiết bin.
  • Nguyên lý: Đặt một hàm_kernel (thường là Gaussian) tại mỗi điểm dữ liệu, cộng chúng lại. Tham số quan trọng: Bandwidth (bw_method / bw_adjust).
    • Bandwidth nhỏ -> Overfitting (gấp ghềnh, bắt chước nhiễu).
    • Bandwidth lớn -> Oversmoothing (mất mode, làm phẳng phân phối).
  • So sánh Histogram vs KDE:

    Tiêu chí Histogram KDE
    Tính giải thích Dễ hiểu cho non-technical (cột = số lượng) Khó hiểu hơn (trục tung = density)
    Độ mượt Phụ thuộc bin Phụ thuộc bandwidth
    Phát hiện Multimodal Tốt nếu bin hợp lý Rất tốt (nếu bw hợp lý)
    So sánh nhiều nhóm Khó (chồng chéo cột) Rất tốt (đường cong màu khác nhau)

💡 Best Practice 2026: Dùng seaborn.histplot(..., kde=True) để có cả hai: Histogram cho trực quan lượng, KDE cho hình dạng mượt. Đặt alpha=0.4 cho histogram để KDE hiện rõ.

2.3. ECDF Plot (Empirical Cumulative Distribution Function) – “Vũ khí so sánh & Thresholding”

Biểu Đồ Phân Phối Của Biến
Biểu Đồ Phân Phối Của Biến
  • Dành cho: So sánh phân phối nhiều nhóm, xác định Percentile/Quantile, thiết lập ngưỡng business (ví dụ: Top 5% khách hàng VIP, SLA latency < 200ms cho 95% request).
  • Ưu điểm: Không cần chọn bin/bandwidth. Bất biến dưới biến đổi đơn điệu (monotonic transformation). Hiển thị trực tiếp xác suất tích lũy.
  • Năm 2026: seaborn.ecdfplot() đã trở thành chuẩn mực, thay thế hoàn toàn việc vẽ CDF thủ công bằng np.sort và np.arange.

2.4. Box Plot & Violin Plot – “Tóm tắt thống kê & Hình dạng kết hợp”

  • Box Plot (Box-and-Whisker):
    • Hiển thị: Median (giữa), Q1/Q3 (hộp), IQR, Whiskers (1.5IQR), Outliers (điểm riêng lẻ).
    • Dùng khi: So sánh phân phối nhiều nhóm (categories) trên một trục tung (ví dụ: Doanh thu theo 12 tháng, Latency theo 5 microservice). Tiết kiệm không gian cực đại.
  • Violin Plot:
    • Kết hợp: Box plot (bên trong) + KDE (bên ngoài, đối xứng).
    • Dùng khi: Cần thấy hình dạng phân phối (multimodal, skew) của từng nhóm mà Box plot giấu đi (Box plot chỉ thấy median/IQR, không thấy bimodal).
  • Strip Plot / Swarm Plot: Vẽ từng điểm dữ liệu (jitter). Dùng khi sample size nhỏ (n < ~100-200). Năm 2026, với data lớn, dùng alpha thấp hoặc rasterized=True để tránh overplotting (chồng điểm).

2.5. Ridge Plot (Joy Plot) – “Xu hướng Storytelling năm 2026”

  • Chồng các KDE/Histogram của nhiều nhóm lên nhau theo trục tung, tạo cảm giác “dãy núi”.
  • Cực kỳ hiệu quả cho: Phân phối theo thời gian (Doanh thu theo tuần/năm), Phân phối điểm số theo lớp/học kỳ, So sánh Latency giữa các version release.
  • Thư viện: joypy (cũ) hoặc custom bằng matplotlib/seaborn FacetGrid. Năm 2026, plotly.express hỗ trợ violin với box và points cho interactive ridge-like view.

2.6. Biểu đồ cho biến Định tính (Categorical) – Đừng quên chúng!

  • Bar Chart (Countplot): Tần suất từng category. Sắp xếp theo thứ tự giảm dần (descending) để dễ đọc nhất.
  • Pie Chart / Donut Chart: KHÔNG KHUYẾN DÙNG cho phân tích chuyên nghiệp (khó so sánh góc/cung). Chỉ dùng cho presentation cấp cao với < 5 category.
  • Treemap / Sunburst: Dùng cho categorical có thứ bậc (Hierarchical) – ví dụ: Phân phối doanh thu theo Khu vực -> Quốc gia -> Tỉnh/Thành.
  • Mosaic Plot: So sánh phân phối có điều kiện của 2 biến categorical (ví dụ: Tỷ lệ Churn theo Giới tính & Gói cước).

Phần 3: Thực Chiến Python 2026 – Code Chuẩn Production, Đẹp, Tương Tác

Môi trường giả định: Python 3.11+, Pandas 2.2+, Seaborn 0.13+, Matplotlib 3.8+, Plotly 5.22+, Polars 1.0+ (cho xử lý data lớn trước khi vẽ).

Chúng ta sẽ dùng dataset giả lập customer_behavior_2026.parquet (định dạng Parquet – chuẩn hiệu năng 2026) chứa: user_id, age, annual_income_vnd, spending_score, loyalty_tier (Bronze, Silver, Gold, Platinum), platform (iOS, Android, Web), churned (0/1), session_duration_sec.

3.1. Setup & Load Data (Hiệu năng cao với Polars -> Pandas)

import polars as pl
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import warnings
warnings.filterwarnings('ignore') # Cấu hình style chuẩn 2026: Accessible, Colorblind-safe, Minimalist
sns.set_theme( style="whitegrid", palette="colorblind", # Quan trọng: Accessibility font="DejaVu Sans", # Font chuẩn hệ thống rc={ "figure.figsize": (12, 7), "axes.titlesize": 16, "axes.labelsize": 13, "xtick.labelsize": 11, "ytick.labelsize": 11, "legend.fontsize": 11, "figure.dpi": 150, # Retina display ready "savefig.dpi": 300, "savefig.bbox": "tight", "savefig.transparent": True # Dễ nhúng vào slide/report dark/light mode }
) # Load data: Polars đọc Parquet siêu nhanh -> convert Pandas để vẽ (Seaborn/Plotly vẫn ưu tiên Pandas)
try: df_pl = pl.read_parquet("data/customer_behavior_2026.parquet") df = df_pl.to_pandas() print(f"Data shape: {df.shape}") print(df.dtypes)
except FileNotFoundError: # Tạo data giả lập nếu không có file để bài viết chạy được ngay print("Generating synthetic data for demo...") np.random.seed(42) n = 50_000 df = pd.DataFrame({ 'user_id': range(n), 'age': np.random.normal(35, 10, n).astype(int).clip(18, 70), 'annual_income_vnd': np.random.lognormal(mean=18, sigma=0.8, size=n).astype(int), # Heavy right skew 'spending_score': np.random.beta(2, 5, n) 100, # Bounded 0-100, left skew 'loyalty_tier': np.random.choice('Bronze', 'Silver', 'Gold', 'Platinum', n, p=0.5, 0.3, 0.15, 0.05), 'platform': np.random.choice('iOS', 'Android', 'Web', n, p=0.3, 0.6, 0.1), 'churned': np.random.binomial(1, 0.15, n), 'session_duration_sec': np.random.gamma(shape=2, scale=150, size=n).astype(int) # Right skew }) # Tạo mối quan hệ thực tế hơn df.locdf'loyalty_tier' == 'Platinum', 'annual_income_vnd' = 3 df.locdf'platform' == 'iOS', 'spending_score' += 15 df'spending_score' = df'spending_score'.clip(0, 100)

3.2. Phân phối biến Liên tục (Numerical) – Deep Dive

A. Histogram + KDE: “Cặp đôi không tách rời”

fig, axes = plt.subplots(2, 2, figsize=(16, 10), constrained_layout=True)
num_cols = 'age', 'annual_income_vnd', 'spending_score', 'session_duration_sec'
titles = 'Tuổi (Gần Normal)', 'Thu nhập năm (Lệch phải mạnh - Log-normal)', 'Điểm chi tiêu (Lệch trái - Beta)', 'Thời gian phiên (Lệch phải - Gamma)' for ax, col, title in zip(axes.flat, num_cols, titles): # Histogram + KDE chuẩn 2026 sns.histplot( data=df, x=col, stat="density", # Quan trọng: Density để so sánh/KDE bins="auto", # Tự động chọn bin (thường là Freedman-Diaconis) kde=True, # Vẽ KDE cùng lúc kde_kws={"bw_adjust": 0.8, "linewidth": 2.5, "color": "crimson"}, # Tinh chỉnh bandwidth color="steelblue", alpha=0.4, edgecolor="white", linewidth=0.5, ax=ax ) # Thêm đường Mean/Median để so sánh Skewness mean_val = dfcol.mean() median_val = dfcol.median() ax.axvline(mean_val, color='red', linestyle='--', linewidth=1.5, label=f'Mean: {mean_val:,.0f}') ax.axvline(median_val, color='green', linestyle=':', linewidth=1.5, label=f'Median: {median_val:,.0f}') ax.set_title(title, fontweight='bold', pad=10) ax.set_xlabel(col.replace('_', ' ').title()) ax.set_ylabel("Density") ax.legend(fontsize=9, frameon=True, facecolor='white', edgecolor='gray') # Format trục x cho tiền tệ/số lớn if 'income' in col: ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x/1e9:.1f}B')) fig.suptitle("Phân Phối Các Biến Số: Histogram + KDE + Mean/Median (2026 Standard)", fontsize=18, fontweight='bold', y=1.02)
plt.show()

Giải thích chuyên sâu:

  • stat="density": Cho phép đường KDE (diện tích=1) khớp hoàn hảo với Histogram.
  • bw_adjust=0.8: Mặc định Seaborn là 1.0 (Scott’s rule). Giảm xuống 0.5-0.8 thường cho KDE “sáng” hơn, bắt được các mode nhỏ (shoulders) trên đuôi phân phối lệch.
  • So sánh Mean (đỏ nét đứt) vs Median (xanh nét chấm): Khoảng cách giữa chúng là độ lệch (Skewness). Thu nhập: Mean >> Median -> Lệch phải cực mạnh.

B. ECDF: So sánh nhóm & Xác định ngưỡng (Thresholding)

# So sánh Session Duration giữa Churned vs Retained
fig, axes = plt.subplots(1, 2, figsize=(16, 6), constrained_layout=True) # 1. ECDF cơ bản
sns.ecdfplot(data=df, x='session_duration_sec', hue='churned', palette={0: 'seagreen', 1: 'indianred'}, linewidth=2.5, stat="proportion", ax=axes0)
axes0.set_title("ECDF: Thời gian phiên theo Trạng thái Churn", fontweight='bold')
axes0.set_xlabel("Session Duration (seconds)")
axes0.set_ylabel("Cumulative Proportion")
axes0.legend(title='Churned', labels='Retained (0)', 'Churned (1)') # 2. Thêm đường ngưỡng Percentile (Business Threshold)
# Ví dụ: Chúng ta muốn biết ngưỡng Top 20% session duration của nhóm Retained
retained_dur = df.locdf.churned==0, 'session_duration_sec'
p80 = retained_dur.quantile(0.80)
axes0.axvline(p80, color='seagreen', linestyle='--', linewidth=2, label=f'P80 Retained: {p80:.0f}s')
axes0.axhline(0.8, color='seagreen', linestyle='--', linewidth=1)
axes0.legend() # 3. ECDF Complementary (1 - CDF) - Survival Function - Hay cho Reliability/Churn
sns.ecdfplot(data=df, x='session_duration_sec', hue='churned', complementary=True, # Vẽ 1 - CDF palette={0: 'seagreen', 1: 'indianred'}, linewidth=2.5, ax=axes1)
axes1.set_title("Survival Function (1-CDF): Xác suất Session > x giây", fontweight='bold')
axes1.set_ylabel("P(Duration > x)")
plt.show()

Insight 2026: ECDF cho thấy ngay: Đường Churned (đỏ) nằm bên trái đường Retained (xanh) -> Người churn có session duration ngắn hơn. Survival function (bên phải) cho thấy % user còn lại sau x giây. Cực quan trọng cho A/B test hoặc thiết lập SLA.

Biểu Đồ Phân Phối Của Biến
Biểu Đồ Phân Phối Của Biến

C. Box Plot vs Violin Plot: So sánh nhiều nhóm (Categorical vs Numerical)

fig, axes = plt.subplots(1, 2, figsize=(18, 7), constrained_layout=True)
order_tier = 'Bronze', 'Silver', 'Gold', 'Platinum' # 1. Box Plot - Tóm tắt nhanh, so sánh Median/IQR/Outlier
sns.boxplot( data=df, x='loyalty_tier', y='annual_income_vnd', order=order_tier, palette="viridis", width=0.6, showcaps=True, boxprops=dict(alpha=0.7), flierprops=dict(marker='o', markersize=3, alpha=0.3, markerfacecolor='red'), # Outlier nhỏ, mờ ax=axes0
)
axes0.set_title("Box Plot: Thu nhập theo Tier (Tóm tắt 5 số + Outlier)", fontweight='bold')
axes0.set_ylabel("Annual Income (VND)")
axes0.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x/1e9:.1f}B')) # 2. Violin Plot - Thấy hình dạng (Multimodal?)
sns.violinplot( data=df, x='loyalty_tier', y='annual_income_vnd', order=order_tier, palette="viridis", inner="box", # Vẽ box plot bên trong violin (Best of both worlds) density_norm="width", # Scale violin bằng width (đẹp hơn cho so sánh) cut=0, # Không extrapolate KDE ra ngoài min/max data ax=axes1
)
axes1.set_title("Violin Plot (+ Inner Box): Hình dạng phân phối Thu nhập theo Tier", fontweight='bold')
axes1.set_ylabel("Annual Income (VND)")
axes1.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x/1e9:.1f}B')) plt.show()

Khi nào dùng cái nào?

  • Box Plot: Báo cáo định kỳ (Weekly/Monthly), dashboard monitoring, so sánh > 10 nhóm, in ấn (static), cần thấy outlier rõ ràng.
  • Violin Plot: Phân tích sâu (Deep dive), báo cáo khoa học, phát hiện phân phối bimodal/multimodal (Box plot sẽ chỉ thấy một hộp to, che giấu 2 đỉnh), presentation cho stakeholder kỹ thuật.

D. Ridge Plot (Joy Plot) – Xu hướng Visualization 2026 cho Time-series/Grouped Dist

# Tạo dữ liệu theo tháng cho demo Ridge Plot
df'month' = np.random.choice(f'2026-{m:02d}' for m in range(1, 13), len(df))
# Sắp xếp tháng
month_order = f'2026-{m:02d}' for m in range(1, 13)
df'month' = pd.Categorical(df'month', categories=month_order, ordered=True) # Dùng FacetGrid của Seaborn để custom Ridge Plot (vì joypy ít update)
g = sns.FacetGrid(df, row='month', hue='month', aspect=5, height=0.6, palette="mako_r", row_order=month_order::-1) # Đảo ngược để tháng 1 trên cùng # Vẽ KDE fill
g.map(sns.kdeplot, 'spending_score', bw_adjust=1, clip=(0, 100), fill=True, alpha=0.8, linewidth=1.5)
# Vẽ đường viền trắng để tách biệt
g.map(sns.kdeplot, 'spending_score', bw_adjust=1, clip=(0, 100), color='white', linewidth=1.2) # Thêm đường baseline (trục x) cho mỗi subplot
def baseline(x, color, kwargs): ax = plt.gca() ax.axhline(0, color='white', linewidth=1.5, zorder=0)
g.map(baseline, 'spending_score') # Format
g.figure.subplots_adjust(hspace=-0.4) # Chồng chéo nhau
g.set_titles(row_template="{row_name}", size=11, fontweight='bold', color='white', x=0, ha='left')
g.set(yticks=, ylabel="", xlabel="Spending Score")
g.despine(bottom=True, left=True)
g.fig.suptitle("Ridge Plot: Phân phối Spending Score theo Tháng (2026)", fontsize=18, fontweight='bold', y=1.02, color='#333')
g.fig.patch.set_facecolor('white')
plt.show()

Tại sao Ridge Plot “hot” năm 2026?

  • Tận dụng vertical space hiệu quả (scroll dọc trên mobile/dashboard).
  • Não bộ người dễ so sánh hình dạng (shape) hơn là vị trí tuyệt đối khi chúng chồng lên nhau.
  • Thẩm mỹ cao, phù hợp cho Data Storytelling, Executive Summary.

3.3. Biến Định Tính (Categorical) – Không Chỉ Là Countplot

fig, axes = plt.subplots(2, 2, figsize=(16, 12), constrained_layout=True)
cat_cols = 'loyalty_tier', 'platform', 'churned' # 1. Countplot chuẩn - Sắp xếp Descending
order_loyalty = df'loyalty_tier'.value_counts().index
sns.countplot(data=df, y='loyalty_tier', order=order_loyalty, palette="viridis", hue='loyalty_tier', legend=False, ax=axes0,0)
axes0,0.set_title("Countplot: Loyalty Tier (Sắp xếp Descending)", fontweight='bold')
axes0,0.bar_label(axes0,0.containers0, fmt='%d', fontsize=11, padding=3)
axes0,0.set_xlabel("Số lượng User") # 2. Percentage Stacked Bar - So sánh tỷ lệ Churn theo Tier (Normalized)
churn_tier = pd.crosstab(df'loyalty_tier', df'churned', normalize='index') 100
churn_tier = churn_tier.reindex(order_loyalty) # Giữ thứ tự
churn_tier.plot(kind='barh', stacked=True, ax=axes0,1, color='seagreen', 'indianred', edgecolor='white', width=0.8)
axes0,1.set_title("Stacked %: Tỷ lệ Churn theo Tier", fontweight='bold')
axes0,1.set_xlabel("Phần trăm (%)")
axes0,1.legend(title='Churned', labels='Retained', 'Churned', frameon=True)
# Thêm label % lên bar
for c in axes0,1.containers: labels = f'{v.get_width():.1f}%' if v.get_width() > 5 else '' for v in c axes0,1.bar_label(c, labels=labels, label_type='center', color='white', fontweight='bold', fontsize=10) # 3. Mosaic Plot (Cần statsmodels) - Tương tác 2 biến Categorical
# from statsmodels.graphics.mosaicplot import mosaic
# mosaic(df, 'platform', 'churned', ax=axes1,0, # properties=lambda key: {'color': 'seagreen' if key1==0 else 'indianred', 'alpha': 0.8})
# axes1,0.set_title("Mosaic Plot: Platform vs Churn", fontweight='bold')
# Thay bằng Heatmap Crosstab cho dễ code chạy ngay:
ct = pd.crosstab(df'platform', df'churned', normalize='index') 100
sns.heatmap(ct, annot=True, fmt=".1f", cmap="RdYlGn_r", center=50, cbar_kws={'label': '%'}, ax=axes1,0)
axes1,0.set_title("Heatmap Crosstab: % Churn theo Platform", fontweight='bold')
axes1,0.set_ylabel("Platform") # 4. Treemap (Plotly Express) - Hierarchical Categorical
# Cần cột phân cấp, giả lập: Region -> Tier
df'region' = np.random.choice('North', 'South', 'Central', len(df), p=0.4, 0.4, 0.2)
treemap_data = df.groupby('region', 'loyalty_tier').size().reset_index(name='count')
fig_treemap = px.treemap(treemap_data, path='region', 'loyalty_tier', values='count', color='count', color_continuous_scale='Viridis', title="Treemap: Phân phối User theo Region -> Tier (Interactive)")
# Lưu file HTML để xem interactive (không show inline được trong script thuần)
fig_treemap.write_html("output/treemap_region_tier.html")
print("Treemap saved to output/treemap_region_tier.html. Mở file HTML để tương tác.") plt.show()

3.4. Interactive Visualization với Plotly – Chuẩn Dashboard/Production 2026

Static image (PNG) đã cũ. Năm 2026, stakeholder yêu cầu hover tooltip, zoom, pan, filter, download PNG/CSV ngay trên biểu đồ. Plotly là vua.

# Interactive Histogram + Box Plot (Violin) kết hợp - "Violin with Points" hoặc "Box + Strip"
# Dùng Plotly Express cho nhanh, Graph Objects cho custom sâu. fig = px.violin( df, x='loyalty_tier', y='annual_income_vnd', color='loyalty_tier', box=True, # Vẽ box plot bên trong points="all", # Vẽ tất cả điểm (cẩn thận với data lớn -> dùng "outliers" hoặc "suspectedoutliers") # points="suspectedoutliers", # Chỉ vẽ outlier theo quy tắc 1.5 IQR hover_data='user_id', 'age', 'platform', # Thông tin khi hover category_orders={'loyalty_tier': order_tier}, color_discrete_sequence=px.colors.sequential.Viridis, title="Interactive Violin + Box + Points: Thu nhập theo Tier (Hover để xem User ID)", labels={'annual_income_vnd': 'Annual Income (VND)', 'loyalty_tier': 'Tier'}, template="plotly_white", # Theme sạch, chuyên nghiệp width=1000, height=600
) # Custom layout nâng cao
fig.update_layout( title_font_size=18, title_x=0.5, showlegend=False, yaxis_tickformat=",.0f", # Format số tiền hovermode="closest", # Thêm annotation giải thích annotations= dict( x=0.5, y=-0.15, xref='paper', yref='paper', text="Violin: KDE shape | Box: Median/IQR/Outliers | Dots: Raw data (Outliers only recommended for >10k pts)", showarrow=False, font=dict(size=11, color="gray"), xanchor='center' ) ) # Tối ưu hiệu năng cho data lớn (50k points): WebGL
fig.update_traces(marker=dict(size=3, opacity=0.3, line=dict(width=0)), selector=dict(type='violin'))
# Chuyển scatter points sang WebGL (Scattergl) nếu cần - Plotly Express violin chưa hỗ trợ trực tiếp scattergl cho points.
# Cách hack: Tạo FigureFactory hoặc Graph Objects thủ công nếu cần 500k+ points. fig.write_html("output/interactive_violin_income.html")
print("Interactive Violin saved. Open in browser.")
# fig.show() # Chạy trong Jupyter/Colab

Plotly Best Practices 2026:

  1. template="plotly_white" hoặc "simple_white": Chuẩn cho báo cáo, dễ embed vào Light/Dark mode web app.
  2. hover_data: Luôn thêm user_id, timestamp, segment_key để drill-down.
  3. Performance: Dữ liệu > 50k rows -> Dùng plotly.graph_objects.Figure + scattergl (WebGL) thay vì px.scatter/px.violin (SVG). SVG sẽ treo trình duyệt.
  4. Export: fig.write_html(..., include_plotlyjs="cdn") để file nhẹ, load JS từ CDN. fig.to_image(format="png", scale=3, engine="kaleido") cho report PDF (cần cài kaleido).

Phần 4: Xử Lý Các Vấn Đề “Thực Tế” Khi Vẽ Phân Phối (Advanced)

4.1. Outlier: Che giấu hay Desensitize?

  • Vấn đề: 1 outlier = 1 tỷ VND làm histogram bị dẹt, KDE bị kéo dài đuôi vô nghĩa.
  • Giải pháp 2026:
    1. Winsorizing/Clipping: Giới hạn ở P1/P99 hoặc P0.5/P99.5 trước khi vẽ (giữ nguyên data gốc cho modeling).
    2. Log Transform: np.log1p(x) cho dữ liệu lệch phải (Income, Duration). Vẽ phân phối của log_income -> Gần Normal, dễ nhìn mode, so sánh nhóm.
    3. Axis Scaling: Dùng xscale="log" trên Matplotlib/Plotly. Giữ dữ liệu gốc, chỉ thay cách hiển thị.
    4. Zoom/Clip View: ax.set_xlim(dfcol.quantile(0.01), dfcol.quantile(0.99)) trên Matplotlib. Plotly cho phép user tự zoom.
# Demo: Log Scale vs Linear Scale cho Income
fig, axes = plt.subplots(1, 2, figsize=(16, 6), constrained_layout=True) # Linear - Bị dẹt
sns.histplot(df'annual_income_vnd', bins=100, stat='density', kde=True, ax=axes0, color='steelblue')
axes0.set_title("Linear Scale: Outlier (Top 0.1%) làm dẹt biểu đồ", fontweight='bold')
axes0.set_xlabel("Income (VND)") # Log Scale - Đẹp, thấy rõ hình dạng Log-Normal
sns.histplot(df'annual_income_vnd', bins=100, stat='density', kde=True, ax=axes1, color='coral')
axes1.set_xscale('log')
axes1.set_title("Log Scale: Phân phối Log-Normal hiện rõ ràng", fontweight='bold')
axes1.set_xlabel("Income (VND) - Log Scale")
# Format tick log
from matplotlib.ticker import ScalarFormatter
axes1.xaxis.set_major_formatter(ScalarFormatter())
axes1.ticklabel_format(style='plain', axis='x') plt.show()

4.2. Multimodal Distribution (Phân phối đa đỉnh) – “Bí mật” của Data Segmentation

Nếu Histogram/KDE có 2 đỉnh (bimodal) hoặc hơn -> Dữ liệu đang trộn lẫn 2 nhóm người/dữ liệu khác nhau.

  • Ví dụ: Thời gian phản hồi API có 2 đỉnh -> 1 đỉnh là Cache Hit (fast), 1 đỉnh là Cache Miss/DB Query (slow).
  • Hành động: Phân tầng (Stratify) bằng biến categorical (ví dụ: cache_status) và vẽ Overlay KDE hoặc Facet Grid.
# Giả lập Bimodal: Mix 2 Gaussian
bimodal_data = np.concatenate( np.random.normal(20, 3, 3000), # Group A: Fast np.random.normal(80, 10, 2000) # Group B: Slow
)
df_bimodal = pd.DataFrame({'latency_ms': bimodal_data})
df_bimodal'group' = 'Fast'3000 + 'Slow'2000 fig, axes = plt.subplots(1, 2, figsize=(14, 5), constrained_layout=True) # 1. Overall - Chỉ thấy 1 đống mờ, hoặc 2 đỉnh gầy gò
sns.histplot(df_bimodal, x='latency_ms', bins=50, stat='density', kde=True, ax=axes0, color='gray')
axes0.set_title("Overall: Bimodal bị che lấp / khó phân tích", fontweight='bold') # 2. Stratified - Overlay KDE (Best for comparison shape)
sns.kdeplot(data=df_bimodal, x='latency_ms', hue='group', fill=True, alpha=0.4, common_norm=False, palette='blue', 'red', linewidth=2, ax=axes1)
sns.rugplot(data=df_bimodal, x='latency_ms', hue='group', palette='blue', 'red', height=0.05, ax=axes1) # Rug plot: thấy điểm dữ liệu thực
axes1.set_title("Stratified by Group: Phát hiện ngay 2 quá trình khác nhau", fontweight='bold')
plt.show()

4.3. Large Data (Big Data) Visualization – Không vẽ 10 triệu điểm

Năm 2026, dataset 10M-100M rows là bình thường.

  • Datashader (HoloViz): Render millions of points thành pixel image (raster) trong ms. Tích hợp với hvPlot / Panel.
  • Vaex: Lazy evaluation + Histogram/Heatmap cực nhanh (out-of-core).
  • Polars + Matplotlib: Agg data trước (binning/quantile) rồi vẽ.
  • Downsampling có ý nghĩa: Systematic sampling (mỗi 1000 row), hoặc Quantile sampling (giữ phân phối).
# Ví dụ: Dùng Polars tính Histogram bin counts siêu nhanh -> vẽ bằng Matplotlib (Bar chart)
# Giả lập 10M rows
# df_big = pl.DataFrame({'value': np.random.normal(0, 1, 10_000_000)})
# hist = df_big.select(pl.col('value').hist(bins=100, bin_range=(-4, 4))) # Polars native hist
# counts = hist'value'.to_numpy()
# bins = np.linspace(-4, 4, 101)
# plt.bar(bins:-1, counts, width=np.diff(bins), align='edge', alpha=0.7)
# -> Vẽ xong 10M rows trong < 1 giây.

Phần 5: Từ Biểu Đồ Đến Insight – Workflow Báo Cáo Chuyên Nghiệp (2026)

Biểu Đồ Phân Phối Của Biến
Biểu Đồ Phân Phối Của Biến

Vẽ xong biểu đồ chưa xong. Năm 2026, Data Storytelling là kỹ năng được trả lương cao nhất.

5.1. Checklist “Sẵn sàng trình bày” (Production Ready)

Trước khi export PNG/HTML/send Slack, kiểm tra:

  • Tiêu đề: Có trả lời được “What, Where, When”? (Ví dụ: “Phân phối Thu nhập năm User Active Tháng 10/2026 Theo Tier” thay vì “Histogram Income”).
  • Trục tọa độ: Có đơn vị (VND, %, Giây, Count)? Có format dễ đọc (1.2B, 50%, 1.5k)?
  • Chú thích (Legend/Annotation): Có giải thích màu sắc, đường nét (Mean/Median, Threshold)?
  • Nguồn dữ liệu & Thời gian: Footer: “Nguồn: DW_Prod, Updated: 2026-11-15 08:00 UTC”.
  • Accessibility: Palette colorblind/viridis/cividis? Contrast ratio > 4.5:1? Không dùng Red/Green cùng lúc cho colorblind (dùng Blue/Orange hoặc Red/Blue).
  • Responsive: Interactive plot (Plotly) test trên mobile (viewport width 375px).

5.2. Template báo cáo Insight (Markdown/Notion/Confluence/Quarto)

## 📊 Insight: Phân phối Thu nhập (Annual Income) - Tháng 11/2026 🎯 Mục tiêu: Hiểu cấu trúc thu nhập để thiết kế gói subscription pricing mới. 📈 Quan sát chính (Key Findings):
1. Phân phối Log-Normal cực mạnh: Mean (2.4B VND) >> Median (1.1B VND). Top 1% user kiếm > 15B VND/năm kéo Mean lên.
2. Bimodal ẩn tại Tier Gold/Platinum: Violin plot cho thấy 2 đỉnh tại Platinum -> Có 2 nhóm: "Whales" (Doanh nhân) & "High-salary Tech/Finance". Cần tách chiến lược chăm sóc.
3. Outlier handling: 0.5% user có income < 50M VND (Sinh viên/Unemployed) -> Nên exclude khỏi tính toán ARPU cho segment Premium. 🛠 Action Items:
- Pricing: Đặt gói Premium tại ~P70 Income của Tier Gold (~1.8B VND/năm ~ 150M/tháng).
- Modeling: Apply `np.log1p(income)` làm feature cho Churn Model thay vì raw income.
- Monitoring: Thiết lập Alert Data Drift nếu Median Income thay đổi > 10% MoM. 📎 Artifacts:
- Interactive Violin Plot (Plotly)(link/to/html)
- Static Report (PDF)(link/to/pdf)
- Notebook Reproducible(link/to/github)

Phần 6: Xu Hướng 2026 Và Tương Lai – Đi Xa Hơn Matplotlib/Seaborn

6.1. Grammar of Graphics (GoG) Native: plotnine (ggplot2 cho Python)

Nếu bạn đến từ R/tidyverse, plotnine cho phép declarative syntax: ggplot(df, aes(x='income')) + geom_histogram(bins=50) + facet_wrap('~tier'). Code ngắn gọn, nhất quán, dễ maintain cho team lớn.

6.2. Declarative Interactive: Altair / Vega-Lite

Chuẩn JSON spec. Rất mạnh cho compound charts (linked brushing: click bar chart -> histogram kia filter theo). Tích hợp tốt với Streamlit/VegaFusion (WebAssembly runtime cho big data).

6.3. GPU-Accelerated Viz: cuGraph / cuxfilter (RAPIDS) / Datashader

Biểu Đồ Phân Phối Của Biến
Biểu Đồ Phân Phối Của Biến

Dữ liệu > 100M rows -> CPU rendering (Matplotlib/Seaborn/Plotly SVG) sẽ die. Phải dùng Datashader (CPU rasterize) hoặc cuxfilter (GPU rasterize) -> output là Image/Tiles -> Hiển thị bằng Panel/Bokeh/Deck.gl.

6.4. AI-Assisted EDA (Auto-Viz)

  • ydata-profiling (trước đây pandas-profiling): Tự động sinh report HTML đầy đủ phân phối, correlation, missing, alerts.
  • SweetViz, AutoViz: So sánh Train/Test, Target analysis.
  • LLM Code Gen (Copilot/Cursor/Claude 3.5 Sonnet/GPT-4o): Năm 2026, bạn không viết code vẽ biểu đồ từ đầu. Bạn prompt: “Vẽ violin plot income by tier, log scale x, inner box, plotly white theme, save html” -> LLM sinh code chuẩn production trong 5s. Kỹ năng cốt lõi chuyển sang: Review code, tùy chỉnh domain-specific, storytelling.

Phần 7: Tổng Kết & Cheat Sheet Nhanh (Quick Reference)

Loại Biến Mục Đích Phân Tích Biểu Đồ Khuyên Dùng (2026) Thư Viện / Function Chính Lưu Ý Quan Trọng
Số (Continuous) Xem hình dạng, Skew, Mode, Outlier Histogram + KDE Overlay sns.histplot(kde=True, stat='density') Dùng bins='auto', bw_adjust=0.5-1. Check Mean vs Median.
Số (Continuous) So sánh nhiều nhóm (Cat vs Num) Violin Plot (inner=”box”) sns.violinplot(inner="box", density_norm="width") cut=0 tránh extrapolate. Dùng order= để sắp xếp nhóm.
Số (Continuous) So sánh nhiều nhóm, compact, outlier rõ Box Plot (Tukey) sns.boxplot(showfliers=True, flierprops=...) Whisker = 1.5 IQR. Outlier = điểm.
Số (Continuous) Xác định Percentile, Threshold, So sánh CDF ECDF / Survival (1-CDF) sns.ecdfplot(complementary=False/True) Không cần bin/bandwidth. Tốt cho SLA/Business Rule.
Số (Continuous) Theo dõi thay đổi theo thời gian/sequence Ridge Plot (Joy Plot) sns.FacetGrid(row=time).map(sns.kdeplot, fill=True) hspace âm để chồng. Palette sequential.
Số (Big Data) 10M+ rows Datashader / Polars Hist / Vaex hvPlot.datashade() / pl.col.hist() Aggregate trước, vẽ sau. Không vẽ raw points.
Danh mục (Categorical) Tần suất, Top K Bar Chart (Horizontal, Sorted Desc) sns.countplot(y=cat, order=vc.index) bar_label cho giá trị. Horizontal dễ đọc label dài.
2 Danh mục Tương tác, Tỷ lệ Stacked % Bar / Heatmap Crosstab / Mosaic pd.crosstab(normalize='index').plot.barh(stacked=True) Stacked % tốt hơn Stacked Count. Mosaic cần statsmodels.
Danh mục Có Cấp Phân phối cây Treemap / Sunburst / Icicle px.treemap(path='L1', 'L2', values='count') Interactive (Plotly) bắt buộc cho drill-down.
Mọi loại Dashboard, Stakeholder, Web App Interactive (Hover, Zoom, Filter) plotly.express / plotly.graph_objects template="plotly_white", hover_data, write_html(include_plotlyjs='cdn').

Lời Kết: “Đừng Chỉ Vẽ Biểu Đồ, Hãy Giải Mã Phân Phối”

Năm 2026, công cụ vẽ biểu đồ đã trở nên commodity (phổ biến, rẻ, dễ dùng). AI có thể sinh code sns.histplot trong tích tắc. Giá trị của bạn – Data Professional – không nằm ở cú pháp matplotlib.pyplot, mà nằm ở:

  1. Tư duy thống kê: Biết tại sao chọn Histogram thay vì KDE, khi nào Log-transform, làm sao phát hiện Bimodal là signal chứ không phải noise.
  2. Kiến thức Domain: Biết rằng “Thu nhập lệch phải” là bình thường, nhưng “Latency lệch trái” là bug hệ thống. Biết ngưỡng P99 latency quan trọng hơn Mean.
  3. Kỹ năng Storytelling: Biến một biểu đồ Violin Plot thành một slide thuyết phục CFO duy ngân sách Marketing.
  4. Engineering Mindset: Viết code reproducible (Jupyter/Quarto + Git), performant (Polars/Datashader cho big data), accessible (colorblind-safe), maintainable (functions/config-driven).

Hy vọng bài viết này – với gần 3000 từ, code thực chiến, tư duy chuyên sâu và chuẩn mực 2026 – sẽ trở thành “Cheat Sheet” trên bàn làm việc của bạn mỗi khi cần đối mặt với câu hỏi: “Dữ liệu này phân phối như thế nào?”.

Hãy vẽ ít hơn, nhưng hiểu sâu hơn. Chúc bạn khai thác insight thành công từ mọi phân phối biến! 🚀

Bài viết được biên soạn dựa trên Best Practices năm 2026: Python 3.11+, Pandas 2.2, Seaborn 0.13, Plotly 5.22, Polars 1.0, Accessibility Standards (WCAG 2.1), Grammar of Graphics Principles.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *