Trong bối cảnh khoa học dữ liệu và thống kê hiện đại đến năm 2026, ngôn ngữ R vẫn giữ vững vị thế là “vua” của việc trực quan hóa dữ liệu thống kê nhờ hệ sinh thái package cực kỳ mạnh mẽ (đặc biệt là ggplot2 và các gói mở rộng). Việc nắm vững cách vẽ biểu đồ phân phối xác suất không chỉ giúp bạn hiểu bản chất dữ liệu mà còn là kỹ năng bắt buộc để truyền cảm hứng insight cho người quyết định. Bài viết này sẽ đi sâu vào từng loại phân phối phổ biến, các kỹ thuật vẽ chuyên nghiệp, tùy chỉnh thẩm mỹ theo xu hướng 2026 và các mẹo xử lý dữ liệu lớn hiệu năng cao.

Phần 1: Cơ Chế Cốt Lõi – Hệ Thống ggplot2 Và Grammar Of Graphics

Trước khi đi vào chi tiết từng phân phối, bạn bắt buộc phải hiểu tư duy ggplot2. Năm 2026, ggplot2 (phiên bản 3.5+) đã tối ưu hóa hiệu năng rendering và hỗ trợ trực tiếp các đối tượng sf (simple features) cho không gian, nhưng cốt lõi vẫn không đổi: Data -> Aesthetics -> Geometry -> Statistics -> Facets -> Coordinates -> Theme.

1.1. Cấu trúc một lệnh vẽ chuẩn

ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>(stat = <STAT>, position = <POSITION>) + <SCALE_FUNCTION> + <FACET_FUNCTION> + <COORD_FUNCTION> + <THEME_FUNCTION>

1.2. Hai triết lý vẽ phân phối quan trọng

  1. Stat=”identity” vs Stat=”density”/”count”: Khi bạn đã có cột xác suất/số lượng tính sẵn -> dùng geom_col() hoặc geom_line(stat="identity"). Khi bạn có dữ liệu thô (raw data) -> dùng geom_histogram(), geom_density(), geom_freqpoly() để R tự tính toán.
  2. Continuous vs Discrete: Phân phối rời rạc (Binomial, Poisson) luôn nên vẽ bằng geom_col()/geom_point()/geom_segment() (lollipop chart), không dùng geom_line() liền mạch vì nó gợi ý sai sự liên tục.

Phần 2: Phân Phối Rời Rạc (Discrete Distributions) – Đồ Họa Chuyên Nghiệp

2.1. Phân Phối Nhị Thức (Binomial Distribution) – dbinom()

Biểu Đồ Phân Phối Xác Suất Trong R
Biểu Đồ Phân Phối Xác Suất Trong R

Ứng dụng 2026: A/B testing conversion rate, kiểm định giả thuyết tỷ lệ, mô hình rủi ro tín dụng.

library(ggplot2)
library(dplyr)
library(tidyr) # Tạo dữ liệu grid tham số để so sánh (Faceting)
params_binom <- expand.grid( n = c(10, 20, 50), p = c(0.2, 0.5, 0.8)
) %>% rowwise() %>% mutate( data = list( tibble( k = 0:n, prob = dbinom(0:n, size = n, prob = p) ) ) ) %>% unnest(data) %>% mutate( label = paste0("n=", n, ", p=", p) ) # Vẽ: Lollipop Chart (Segment + Point) - Chuẩn mực 2026 cho phân phối rời rạc
ggplot(params_binom, aes(x = k, y = prob)) + geom_segment(aes(xend = k, yend = 0), color = "steelblue", linewidth = 1.2) + geom_point(size = 3, color = "steelblue", fill = "white", shape = 21, stroke = 1.5) + facet_wrap(~ label, scales = "free_y", ncol = 3) + labs( title = "Phân Phối Nhị Thức: Sự Thay Đổi Hình Dáng Theo n và p", subtitle = "Năm 2026: Ưu tiên Lollipop Chart thay vì Bar Chart để giảm 'mực in' (ink ratio)", x = "Số lần thành công (k)", y = "Xác suất P(X=k)", caption = "Nguồn: Mô phỏng R 4.4+" ) + theme_minimal(base_size = 13, base_family = "Roboto") + # Font hiện đại theme( panel.grid.minor = element_blank(), strip.text = element_text(face = "bold", size = 11), plot.title.position = "plot", plot.caption.position = "plot" )

💡 Mẹo 2026: Dùng geom_segment + geom_point (Lollipop) thay vì geom_col. Nó giảm “tỷ lệ mực dữ liệu” (Data-Ink Ratio – Tufte), giúp mắt tập trung vào vị trí xác suất chính xác hơn, đặc biệt khi n lớn (nhiều thanh cạnh nhau).

2.2. Phân Phối Poisson (dpois()) – Mô Hình Số Lượng Sự Kiện Hiếm

Bối cảnh: Số lượng đơn hàng/giây, số lỗi code/1000 dòng, lượng truy cập webhook.

lambdas <- c(1, 3, 5, 10, 20)
pois_data <- lapply(lambdas, function(l) { k_max <- qpois(0.999, l) # Chỉ vẽ đến quantile 0.999 để tiết kiệm không gian tibble(k = 0:k_max, prob = dpois(0:k_max, l), lambda = paste0("λ = ", l))
}) %>% bind_rows() ggplot(pois_data, aes(x = k, y = prob)) + geom_col(fill = "#E69F00", alpha = 0.8, width = 0.7, color = "white", linewidth = 0.2) + geom_text(aes(label = ifelse(prob > 0.05, sprintf("%.2f", prob), "")), vjust = -0.3, size = 3, family = "Roboto") + # Chỉ label đỉnh cao facet_wrap(~ lambda, scales = "free", nrow = 1) + scale_y_continuous(expand = expansion(mult = c(0, 0.15))) + # Không gian cho text label labs(title = "Phân Phối Poisson: Từ Hiếm (λ=1) Đến Gần Chuẩn (λ=20)", x = "Số sự kiện (k)", y = "Xác suất") + theme_classic(base_size = 12) + theme(strip.background = element_rect(fill = "grey90", color = NA))

Lưu ý kỹ thuật: Khi lambda > 20, Poisson xấp xỉ Normal. Năm 2026, ta thường overlay đường cong Normal (stat_function(fun = dnorm, args = list(mean=lambda, sd=sqrt(lambda)))) lên histogram Poisson để chứng minh định lý giới hạn trung tâm.

2.3. Phân Phối Geometric & Negative Binomial – Thời Gian Chờ & Overdispersion

Dùng dgeom() và dnbinom(). dnbinom quan trọng trong RNA-seq (Bioinformatics) và Bảo hiểm (số claim) nơi phương sai > trung bình (overdispersion).

# So sánh Geometric (k=1) vs NegBin (k>1)
negbin_data <- bind_rows( tibble(k = 0:20, prob = dnbinom(0:20, size = 1, mu = 3), dist = "Geometric (k=1)"), tibble(k = 0:20, prob = dnbinom(0:20, size = 2, mu = 3), dist = "NegBin (k=2)"), tibble(k = 0:20, prob = dnbinom(0:20, size = 5, mu = 3), dist = "NegBin (k=5)")
) ggplot(negbin_data, aes(x = k, y = prob, fill = dist)) + geom_col(position = "dodge", width = 0.6, alpha = 0.85) + scale_fill_viridis_d(option = "plasma", end = 0.8) + # Colorblind-safe palette 2026 labs(title = "Negative Binomial: Tham Số Size (k) Kiểm Soát Độ Phân Tan", subtitle = "Cùng mean=3. Size nhỏ -> đuôi dày hơn (Overdispersion)") + theme_minimal()

Phần 3: Phân Phối Liên Tục (Continuous Distributions) – Nghệ Thuật Đường Cong Mật Độ

Đây là nơi ggplot2 tỏa sáng nhất với stat_function, geom_density, geom_area.

3.1. Phân Phối Chuẩn (Normal/Gaussian) – “Xương Sống” Của Thống Kê

3.1.1. Vẽ đường cong lý thuyết chuẩn nhất (Base R vs ggplot2)

# Cách 1: stat_function (Nhanh, chính xác toán học, không cần data frame)
p_norm_base <- ggplot(data.frame(x = c(-4, 4)), aes(x)) + stat_function(fun = dnorm, args = list(mean = 0, sd = 1), linewidth = 1.2, color = "#0072B2") + labs(title = "Phân Phối Chuẩn Chuẩn (μ=0, σ=1)", y = "Mật độ f(x)") # Cách 2: Tự tạo data frame (Linh hoạt cho fill area, annotation phức tạp)
x_grid <- seq(-4, 4, length.out = 500)
norm_df <- data.frame(x = x_grid, y = dnorm(x_grid, 0, 1)) ggplot(norm_df, aes(x, y)) + geom_area(fill = "#0072B2", alpha = 0.3) + geom_line(linewidth = 1, color = "#0072B2") + # Tô màu vùng đuôi 2.5% (Critical region alpha=0.05 two-tailed) geom_area(data = subset(norm_df, x < qnorm(0.025) | x > qnorm(0.975)), fill = "#D55E00", alpha = 0.5) + geom_vline(xintercept = c(qnorm(0.025), qnorm(0.975)), linetype = "dashed", color = "#D55E00", linewidth = 0.8) + annotate("text", x = -3, y = 0.02, label = "α/2 = 0.025", color = "#D55E00", size = 4) + annotate("text", x = 3, y = 0.02, label = "α/2 = 0.025", color = "#D55E00", size = 4) + labs(title = "Vùng Bác Bỏ Giả Thuyết (Rejection Region) α=0.05", subtitle = "Kỹ thuật: subset() trong geom_area để tô vùng đuôi chọn lọc") + theme_minimal(base_family = "Roboto")

3.1.2. So sánh nhiều đường Normal (Faceting vs Overlay)

# Overlay: Dùng khi so sánh hình dáng (scale y giống nhau)
# Faceting: Dùng khi tham số scale y khác biệt lớn (vd: sd=0.5 vs sd=5) params_norm <- expand.grid(mean = c(0, 2), sd = c(0.5, 1, 2))
norm_curves <- params_norm %>% rowwise() %>% mutate(data = list( tibble(x = seq(mean - 4sd, mean + 4sd, length.out = 300), y = dnorm(x, mean, sd)) )) %>% unnest(data) %>% mutate(group = paste0("μ=", mean, ", σ=", sd)) ggplot(norm_curves, aes(x, y, color = group)) + geom_line(linewidth = 1) + scale_color_viridis_d(option = "D", end = 0.9) + labs(title = "Hội Tụ Phân Phối Chuẩn: Tác Động Của Mean & SD", color = "Tham số") + theme_minimal() + theme(legend.position = "bottom")

3.2. Phân Phối T-Student (dt()) – Khi Mẫu Nhỏ, Sigma Không Biết

Biểu Đồ Phân Phối Xác Suất Trong R
Biểu Đồ Phân Phối Xác Suất Trong R

Quan trọng 2026: Dùng trong Bootstrap Confidence Intervals, Bayesian Posterior Predictive Checks (khi prior vague).

dfs <- c(1, 2, 5, 10, 30, Inf) # Inf = Normal
t_data <- lapply(dfs, function(df) { x <- seq(-4, 4, length.out = 400) y <- if(is.infinite(df)) dnorm(x) else dt(x, df) tibble(x = x, y = y, df = ifelse(is.infinite(df), "Normal (∞)", paste0("df = ", df)))
}) %>% bind_rows() ggplot(t_data, aes(x, y, color = df)) + geom_line(linewidth = 1) + scale_color_brewer(palette = "Set1") + labs(title = "Phân Phối T Student: Hội Tụ Về Chuẩn Khi df Tăng", subtitle = "df=1 là Cauchy (đuôi cực dày, không có mean/variance)") + theme_minimal()

Insight: Năm 2026, với Big Data, df thường rất lớn -> T ≈ Normal. Nhưng trong Meta-analysis (kết hợp nghiên cứu nhỏ) hoặc Small Area Estimation, hiểu đuôi dày của T là sinh tử.

3.3. Phân Phối Chi-Bình Phương (dchisq()) & F (df()) – Kiểm Định & ANOVA

Đặc trưng: Chỉ định nghĩa trên x ≥ 0, lệch phải (right-skewed).

# Chi-square
chi_df <- data.frame( x = seq(0, 30, length.out = 500), df1 = dchisq(seq(0, 30, length.out = 500), df = 1), df3 = dchisq(seq(0, 30, length.out = 500), df = 3), df10 = dchisq(seq(0, 30, length.out = 500), df = 10)
) %>% pivot_longer(-x, names_to = "df", values_to = "y") ggplot(chi_df, aes(x, y, color = df)) + geom_line(linewidth = 1) + scale_x_continuous(breaks = seq(0, 30, 5)) + labs(title = "Phân Phối Chi-Bình Phương: Độ Lệch Phụ Thuộc bậc Tự Do", x = "Giá trị thống kê χ²", y = "Mật độ") + theme_minimal()

3.4. Phân Phối Exponential (dexp()) & Gamma (dgamma()) – Mô Hình Thời Gian & Rate

Exponential là trường hợp đặc biệt của Gamma (shape=1). Gamma linh hoạt mô hình hóa thời gian chờ, lượng mưa, claim size (bảo hiểm).

# Gamma: shape (k) vs rate (theta) vs scale (1/rate)
# Parameterization trong R: dgamma(x, shape, rate) HOẶC dgamma(x, shape, scale=1/rate)
# CẢNH BÁO 2026: Luôn kiểm tra ?dgamma. Mặc định là rate. gamma_params <- tibble( shape = c(0.5, 1, 2, 5, 10), rate = 1
) %>% rowwise() %>% mutate(data = list( tibble(x = seq(0, qgamma(0.999, shape, rate), length.out = 400), y = dgamma(x, shape, rate)) )) %>% unnest(data) %>% mutate(label = paste0("Shape=", shape, ", Rate=1")) ggplot(gamma_params, aes(x, y, color = label)) + geom_line(linewidth = 1) + labs(title = "Phân Phối Gamma: Shape Kiểm Soát Hình Dáng (Từ Lệch -> Cân Xứng)", subtitle = "Shape < 1: J-shaped (như Exp). Shape > 1: Unimodal. Lớn -> Normal") + theme_minimal()

3.5. Phân Phối Beta (dbeta()) – “Vua” Của Bayesian & Tỷ Lệ

Định nghĩa trên 0, 1. Cực kỳ quan trọng trong A/B Testing (Bayesian), Dirichlet Process, mô hình xác suất thành công.

beta_params <- tribble( ~a, ~b, ~desc, 0.5, 0.5, "U-shape (Bimodal ở 0 và 1)", 1, 1, "Uniform (Prior không thông tin)", 2, 2, "Symmetric Unimodal (Đỉnh ở 0.5)", 5, 2, "Lệch Phải (Mode ~ 0.67)", 2, 5, "Lệch Trái (Mode ~ 0.33)", 10, 10, "Rất tập trung quanh 0.5 (Prior mạnh)"
) beta_curves <- beta_params %>% rowwise() %>% mutate(data = list( tibble(x = seq(0, 1, length.out = 500), y = dbeta(x, a, b)) )) %>% unnest(data) ggplot(beta_curves, aes(x, y, color = desc)) + geom_line(linewidth = 1.2) + scale_color_viridis_d(option = "turbo", end = 0.9) + # Turbo palette đẹp mắt 2026 labs(title = "Phân Phối Beta: Linh Hoạt Mô Hình Hóa Niềm Tin Về Tỷ Lệ", subtitle = "a=Successes+1, b=Failures+1 (Prior Jeffreys/Bayes-Laplace)", x = "Xác suất thành công (p)", y = "Mật độ Prior/Posterior") + theme_minimal(base_size = 13) + theme(legend.position = "right")

Phần 4: Trực Quan Hóa Dữ Liệu Thực Tế (Empirical Distributions) – Năm 2026

Khi có dữ liệu thô (raw data), chúng ta không vẽ hàm toán học mà ước lượng phân phối.

4.1. Histogram & Density Plot – Cặp Đôi Không Thể Tách

Biểu Đồ Phân Phối Xác Suất Trong R
Biểu Đồ Phân Phối Xác Suất Trong R

Vấn đề kinh điển: Chọn bins / binwidth cho Histogram; Chọn bw (bandwidth) cho Density.

set.seed(2026)
# Dữ liệu mô phỏng: Mixture của 2 Normal (Bimodal)
raw_data <- tibble( value = c(rnorm(500, mean = -2, sd = 1), rnorm(500, mean = 3, sd = 1.5)), group = "Mixture"
) # Best Practice 2026: Overlay Histogram (density scale) + Density Curve + Rug
ggplot(raw_data, aes(x = value)) + # Histogram trên thang mật độ (density) để so sánh với geom_density geom_histogram(aes(y = after_stat(density)), bins = 40, fill = "grey80", color = "white", linewidth = 0.2) + # Đường Kernel Density Estimate (KDE) geom_density(linewidth = 1.2, color = "#0072B2") + # Rug plot (vạch nhỏ dưới trục x) - thể hiện từng điểm dữ liệu geom_rug(sides = "b", alpha = 0.3, length = unit(0.02, "npc")) + labs(title = "Histogram + KDE + Rug: Chuẩn Mực EDA Năm 2026", subtitle = "Dùng after_stat(density) để cân bằng trục y giữa Histogram và Density", y = "Mật độ ước lượng") + theme_minimal()

💡 Giải thích after_stat(density): Trong ggplot2 3.4+, ..density.. đã deprecated. after_stat(density) là cú pháp mới chuẩn cho stat_bin/stat_density.

4.2. Frequency Polygon (geom_freqpoly) – So Sánh Nhóm Hiệu Quả

Tốt hơn Histogram khi so sánh nhiều nhóm trên cùng một biểu đồ (tránh chồng chéo thanh bar).

# So sánh 3 nhóm
compare_data <- tibble( value = c(rnorm(1000, 0, 1), rnorm(1000, 2, 1.5), rnorm(1000, -1, 0.5)), group = rep(c("Control", "Treatment A", "Treatment B"), each = 1000)
) ggplot(compare_data, aes(x = value, color = group, linetype = group)) + geom_freqpoly(binwidth = 0.3, linewidth = 1.1) + scale_color_manual(values = c("#0072B2", "#D55E00", "#009E73")) + labs(title = "Frequency Polygon: So Sánh Phân Phối Nhiều Nhóm", subtitle = "Tính năng: Dễ thấy sự dịch chuyển trung tâm (shift) và thay đổi spread") + theme_minimal()

4.3. Q-Q Plot (Quantile-Quantile) – Kiểm Tra Giả Định Chuẩn “Chuẩn”

geom_qq + geom_qq_line. Năm 2026, ta dùng stat_qq_band (từ package qqplotr hoặc tự code bootstrap) để thêm đường tin cậy (Confidence Envelope).

# Cài đặt: install.packages("qqplotr")
library(qqplotr) ggplot(raw_data, aes(sample = value)) + stat_qq_band(alpha = 0.3, fill = "grey50") + # Vùng tin cậy 95% (Bootstrap/Analytic) stat_qq_line(color = "#D55E00", linewidth = 1) + # Đường tham chiếu stat_qq_point(alpha = 0.5, size = 1.5, color = "#0072B2") + # Điểm dữ liệu labs(title = "Q-Q Plot Với Confidence Band (qqplotr)", subtitle = "Nếu điểm nằm ngoài band đỏ -> Bác bỏ giả định Normal", x = "Theoretical Quantiles", y = "Sample Quantiles") + theme_minimal()

Phần 5: Kỹ Thuật Nâng Cao & Xu Hướng 2026

5.1. Ridgeline Plots (Joy Plots) – So Sánh Phân Phối Theo Thời Gian/Nhóm

Package ggridges. Cực hot cho Climate Change visualization, Single-cell RNA-seq, Salary distribution by year.

# install.packages("ggridges")
library(ggridges) # Mô phỏng lương theo năm (tăng dần + spread dần)
salary_data <- tibble( year = rep(2015:2025, each = 200), salary = c(sapply(2015:2025, function(y) rlnorm(200, meanlog = log(10 + (y-2015)1.5), sdlog = 0.5 - (y-2015)0.02)))
) ggplot(salary_data, aes(x = salary, y = factor(year), fill = factor(year))) + geom_density_ridges( scale = 1.5, rel_min_height = 0.01, alpha = 0.7, color = "white", linewidth = 0.3 ) + scale_fill_viridis_d(option = "magma", direction = -1, guide = "none") + scale_x_continuous(labels = scales::label_dollar(suffix = "K")) + labs(title = "Ridgeline Plot: Phân Phối Lương Theo Năm (2015-2025)", subtitle = "Xu hướng: Trung bình tăng, sự chênh lệch giảm (sdlog giảm)", x = "Lương (Nghìn $)", y = "Năm") + theme_ridges(font_family = "Roboto", center_axis_labels = TRUE) + theme(plot.title.position = "plot")

5.2. Violin Plot + Boxplot + Raw Data (Raincloud Plot) – “All-in-One”

Kết hợp geom_violin, geom_boxplot (width nhỏ), geom_jitter/geom_point. Package ggrain hoặc ggdist tự động hóa điều này.

# install.packages("ggdist") - Package hiện đại nhất 2024-2026 cho distributional viz
library(ggdist) ggplot(compare_data, aes(x = group, y = value, fill = group)) + # Slab (Violin/Density) + Interval (Boxplot/Quantiles) + Point (Raw data) stat_slabinterval( .width = c(0.5, 0.8, 0.95), # Các quantile interval slab_type = "pdf", # Vẽ density curve slab_size = 0.5, interval_size_range = c(1, 3), point_interval = "median_qi", # Median + Quantile Interval side = "both" # Violin đối xứng ) + scale_fill_manual(values = c("#0072B2", "#D55E00", "#009E73"), guide = "none") + coord_flip() + # Ngay ngắn hơn, dễ đọc label nhóm labs(title = "Raincloud Plot (ggdist): Tổng Hợp Toàn Diện", subtitle = "Slab=Density, Dot=Raw Data, Bar=Median, Thick/Thin Line=50%/95% CI", x = NULL, y = "Giá trị đo lường") + theme_minimal(base_family = "Roboto")

Tại sao ggdist thắng ggplot2 thuần túy năm 2026?

  1. Tự động xử lý slab (density), interval (CI), point (data) trong một geom.
  2. Hỗ trợ trực tiếp các đối tượng posterior draws từ brms/rstanarm (Bayesian workflow).
  3. Tính toán quantile interval chính xác (HDI – Highest Density Interval) thay vì chỉ symmetric CI.

5.3. Trực Quan Hóa Posterior Distribution (Bayesian Workflow)

Biểu Đồ Phân Phối Xác Suất Trong R
Biểu Đồ Phân Phối Xác Suất Trong R

Năm 2026, Bayesian không còn niche. ggdist::stat_halfeye() là chuẩn.

# Giả lập posterior draws cho 3 tham số
posterior_draws <- tibble( param = rep(c("beta1", "beta2", "sigma"), each = 4000), value = c(rnorm(4000, 1.5, 0.2), rnorm(4000, -0.5, 0.1), rgamma(4000, shape = 20, rate = 10))
) ggplot(posterior_draws, aes(x = value, y = param, fill = param)) + stat_halfeye( .width = c(0.5, 0.8, 0.95), slab_color = "white", slab_size = 0.5, point_interval = "median_qi" ) + scale_fill_brewer(palette = "Set2", guide = "none") + labs(title = "Half-Eye Plot: Posterior Distributions (Bayesian)", subtitle = "Thick line: 50% HDI, Thin line: 95% HDI, Dot: Median", x = "Giá trị tham số", y = NULL) + theme_minimal()

5.4. Hiệu Năng Với Big Data (10M+ rows) – geom_hex, stat_density_2d, datashader (via ggplot2 + rasterize)

Vẽ 10 triệu điểm geom_point -> treo máy. Giải pháp 2026:

  1. Downsampling: dplyr::slice_sample(n = 50000) trước khi vẽ.
  2. Hexbin / 2D Density: geom_hex(bins = 100) hoặc stat_density_2d(geom = "raster", contour = FALSE).
  3. ggrastr::rasterize(): Vẽ vector phức tạp (violin, ridges) nhưng raster hóa layer điểm để file PDF/PNG nhẹ, mở nhanh.
# Ví dụ rasterize layer jitter lớn
library(ggrastr) big_data <- tibble(x = rnorm(1e6), y = rnorm(1e6, mean = 2)) ggplot(big_data, aes(x, y)) + # Rasterize chỉ layer điểm, giữ axis/legend vector rasterise(geom_point(alpha = 0.1, size = 0.3, color = "#0072B2"), dpi = 300) + geom_density_2d(color = "red", linewidth = 0.5) + labs(title = "Big Data Viz: 1 Triệu Điểm Với ggrastr::rasterise", subtitle = "File PDF output nhẹ, zoom không vỡ axis text") + theme_minimal()

Phần 6: Tùy Chỉnh Thẩm Mỹ (Theming) Chuẩn Xuất Bản 2026

Một biểu đồ phân phối đẹp phải tuân thủ: Accessibility (Colorblind safe), Typography (System fonts), Minimalism (Tufte).

6.1. Theme Tùy Chỉnh Có Thể Tái Sử Dụng (theme_my2026)

theme_my2026 <- function(base_size = 12, base_family = "Roboto") { theme_minimal(base_size = base_size, base_family = base_family) %+replace% theme( # Title/Subtitle/Caption positioning plot.title.position = "plot", plot.caption.position = "plot", plot.title = element_text(face = "bold", size = rel(1.4), margin = margin(b = 4)), plot.subtitle = element_text(color = "grey30", size = rel(1.1), margin = margin(b = 12)), plot.caption = element_text(color = "grey50", size = rel(0.8), hjust = 0, margin = margin(t = 12)), # Axis axis.title = element_text(face = "bold", color = "grey20"), axis.text = element_text(color = "grey30"), axis.line = element_line(color = "grey80", linewidth = 0.4), axis.ticks = element_line(color = "grey80", linewidth = 0.3), # Grid panel.grid.major = element_line(color = "grey92", linewidth = 0.3), panel.grid.minor = element_blank(), # Legend legend.position = "top", legend.justification = "left", legend.direction = "horizontal", legend.title = element_text(face = "bold", size = rel(0.9)), legend.text = element_text(size = rel(0.9)), legend.key.size = unit(1.2, "lines"), legend.margin = margin(b = -10), # Facet strip.text = element_text(face = "bold", size = rel(1), hjust = 0, margin = margin(b = 6, t = 6)), strip.background = element_rect(fill = "grey95", color = NA), # Plot margin plot.margin = margin(12, 12, 12, 12) )
} # Áp dụng ngay
ggplot(norm_df, aes(x, y)) + geom_area(fill = "#0072B2", alpha = 0.4) + geom_line(color = "#0072B2", linewidth = 1) + labs(title = "Áp Dụng Theme Chuẩn 2026", subtitle = "Font Roboto, Colorblind-safe palette, Minimal grid", x = "Giá trị", y = "Mật độ") + theme_my2026()

6.2. Màu Sắc (Color Palettes) – Bắt Buộc Colorblind Safe

  • Viridis family: viridis, magma, plasma, inferno, cividis, turbo (mặc định scale_color_viridis_d/c).
  • Okabe-Ito (Color Universal Design): c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#000000"). Dùng scale_color_manual(values = okabe_ito).
  • Không dùng: Jet/Rainbow, Red-Green cùng lúc.

Phần 7: Xuất Bản & Tích Hợp (Quarto, Shiny, Interactive)

7.1. Quarto (Thay thế R Markdown năm 2026)

Xuất ra HTML/PDF/DOCX/PPTX với cấu hình YAML chuẩn.

# _quarto.yml hoặc header .qmd
format: html: theme: cosmo toc: true code-fold: true fig-width: 8 fig-height: 5 fig-retina: 2 # High DPI cho màn hình Retina/4K pdf: documentclass: article geometry: margin=1in fig-width: 6.5 fig-height: 4

7.2. Interactivity với plotly & ggiraph

Biểu Đồ Phân Phối Xác Suất Trong R
Biểu Đồ Phân Phối Xác Suất Trong R
  • ggplotly(p): Hover tooltip tự động, zoom, pan. Nhược điểm: Nặng, không render tốt LaTeX math trong tooltip.
  • ggiraph::girafe(ggobj = p): Ưu tiên 2026. Hỗ trợ tooltip, onclick, data_id cho Shiny. Giữ nguyên theme ggplot2. File HTML nhẹ hơn Plotly.
library(ggiraph) p_interactive <- ggplot(norm_df, aes(x, y)) + geom_area_interactive(aes(tooltip = sprintf("x=%.2f\ny=%.4f", x, y), data_id = x), fill = "#0072B2", alpha = 0.4) + geom_line_interactive(aes(tooltip = sprintf("Density: %.4f", y)), color = "#0072B2", linewidth = 1) + labs(title = "Interactive Normal Density (ggiraph)", subtitle = "Hover để xem tọa độ chính xác") + theme_my2026() girafe(ggobj = p_interactive, options = list( opts_hover(css = "fill:#D55E00;stroke:#D55E00;"), # Hover effect opts_tooltip(css = "background:white;color:black;padding:5px;border-radius:3px;box-shadow: 0 0 5px grey;"), opts_sizing(rescale = TRUE) # Responsive ))

7.3. Shiny Module cho Distribution Explorer

Tạo module mod_dist_explorer.R cho phép user chọn distribution, params, sample size -> vẽ real-time.

# UI
distExplorerUI <- function(id) { ns <- NS(id) tagList( sidebarLayout( sidebarPanel( selectInput(ns("dist"), "Distribution", choices = c("Normal", "t-Student", "Chi-sq", "F", "Beta", "Gamma", "Binomial", "Poisson")), # Dynamic UI for params (renderUI in server) uiOutput(ns("params_ui")), sliderInput(ns("n"), "Sample Size (Overlay Empirical)", 0, 5000, 500, step = 100), checkboxInput(ns("show_theory"), "Show Theoretical Curve", TRUE) ), mainPanel( girafeOutput(ns("plot"), height = "600px") ) ) )
} # Server (Logic phức tạp: switch case cho params, r()/d() functions)
# ... (Code server khá dài, nguyên tắc: dùng reactive({}) tính toán data, renderGirafe({}) vẽ)

Phần 8: Checklist Chẩn Đoán & Khắc Phục Sự Cố (Troubleshooting)

Vấn đề Nguyên nhân Giải pháp 2026
Đường Density bị gợn sóng/nhiễu Bandwidth (bw) quá nhỏ (overfitting) Tăng adjust trong geom_density(adjust = 2) hoặc dùng bw = "SJ" (Sheather-Jones).
Histogram thay đổi hình dáng khi resize bins mặc định = 30, không ổn định Luôn set binwidth (dựa trên IQR/Freedman-Diaconis) hoặc bins cố định.
QQ Plot cong nhưng dữ liệu lớn Với Big Data, QQ plot luôn significant (p < 0.05) do power cao Dùng QQ Plot với Confidence Band (qqplotr). Chỉ lo nếu điểm lệch ngoài band và lệch hệ thống (hình chữ S).
Violin plot bị cắt đầu (clipped) Density estimate vượt ra ngoài range data geom_violin(trim = FALSE) (mặc định TRUE).
Gamma/Exponential vẽ sai trục âm dgamma/dexp trả về 0 cho x<0, nhưng geom_area vẽ nối xuống 0 Dùng xlim(c(0, NA)) hoặc coord_cartesian(xlim = c(0, max_x)).
Màu in ra báo cáo đen trắng (grayscale) không phân biệt Dùng màu sắc hue khác nhau nhưng lightness giống nhau Test bằng colorspace::desaturate(p) hoặc in thử. Dùng viridis hoặc pattern (ggpattern) cho fill.
File PDF/PNG quá to (50MB+) Vẽ raw points (geom_point) cho 1M+ rows Bắt buộc dùng ggrastr::rasterise() hoặc geom_hex/stat_density_2d.

Phần 9: Tài Nguyên Học Tập & Gói Mở Rộng (Packages) “Must-Have” Năm 2026

  1. Core: ggplot2 (>= 3.5), dplyr, tidyr, purrr.
  2. Distributional Viz Specialists:
    • ggdist / distributional: Top 1 cho Bayesian, posterior, predictive checks.
    • ggridges: Ridgeline plots.
    • qqplotr: Q-Q plots với confidence bands.
    • ggrain / see: Raincloud plots (alternative to ggdist).
  3. Performance & Big Data:
    • ggrastr: Rasterize layers.
    • hexbin / ggforce::geom_hex: Hexbinning.
    • datashader (via Python/reticulate hoặc ggplot2 + rasterize): Cực limit.
  4. Interactivity: ggiraph (ưu tiên), plotly.
  5. Color & Theme: viridis, colorspace, ggthemes, thematic (auto theme cho Shiny/Quarto).
  6. Statistical Backend: distributional (object-oriented distributions), posterior (mcmc draws).
  7. Documentation: Quarto (CLI), pkgdown (cho package dev).

Kết Luận: Từ Vẽ Biểu Đồ Đến “Kể Chuyện Với Dữ Liệu”

Năm 2026, vẽ biểu đồ phân phối xác suất trong R không còn là gõ lệnh hist(x) hay plot(density(x)). Nó là quy trình:

  1. Hiểu bản chất toán học: Rời rạc vs Liên tục, Tham số hóa (Rate vs Scale), Hỗ trợ (Support).
  2. Chọn Geometry đúng: Lollipop (Rời rạc), Area/Line (Liên tục lý thuyết), Histogram/Density/Ridgeline/Raincloud (Dữ liệu thực).
  3. Truyền đạt không xác định: Luôn vẽ kèm Confidence Intervals, HDI, Quantile Bands (ggdist, qqplotr).
  4. Thẩm mỹ & Truy cập: Colorblind-safe (Viridis/Okabe-Ito), Font system (Roboto/Inter), Theme Minimal (Tufte).
  5. Hiệu năng & Triển khai: ggrastr cho Big Data, ggiraph cho Web/Shiny, Quarto cho báo cáo tái lập.

Hy vọng bài viết này (với hơn 2500 từ, code chạy thực tế, tư duy 2026) trang bị cho bạn “vũ khí” mạnh nhất để chinh phục mọi thử thách trực quan hóa phân phối xác suất. Hãy clone code, thử nghiệm params, và xây dựng theme riêng của bạn ngay hôm nay!

Lưu ý cuối: Luôn cập nhật package (update.packages(ask = FALSE)) và đọc NEWS.md của ggplot2, ggdist để nắm tính năng mới (ví dụ: after_stat(), stat_slabinterval(), geom_density_ridges() improvements). Chúc bạn vẽ được những biểu đồ “đẹp như ảnh, đúng như toán”!

Để 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 *