如何在R语言norm_f()函数中集成log2转换可视化并生成2×2正态分布评估图
Updated
norm_f() Function for 2x2 Normality Assessment Grid Got it! Here's a refined version of your norm_f() function that generates a 2×2 plot grid—showing normality assessments for both the original variable and its log2-transformed counterpart. I've also added a safety check to avoid errors with non-positive values (since log2 can't handle those):
norm_f <- function(z, hist. = list(col = "lightgray"), lines. = list(lwd = 2), curve. = list(col = "red", lwd = 2), qqnorm. = list(col = "black", pch = 1, cex = 1.2), qqline. = list(lwd = 2)) { zname <- deparse(substitute(z)) # Prevent log2 transformation errors for non-positive values if (any(z <= 0)) { stop(paste("Can't log2-transform", zname, "- contains values ≤ 0")) } z_log2 <- log2(z) z_log2_label <- paste("log2(", zname, ")", sep = "") # Set up 2×2 plot layout par(mfrow = c(2, 2), mar = c(5, 5, 2, 2)) # Reusable helper to plot normality for a single variable plot_single_norm <- function(var, var_label) { var_density <- density(var) hist_params <- hist. # Auto-set ylim if not provided if (!"ylim" %in% names(hist_params)) { y_max <- max(var_density$y, dnorm(seq(min(var), max(var), len = 21), mean = mean(var), sd = sd(var))) hist_params$ylim <- c(0, y_max) } # Auto-set plot labels if not provided if (!"main" %in% names(hist_params)) hist_params$main <- paste("Histogram of", var_label) if (!"xlab" %in% names(hist_params)) hist_params$xlab <- var_label # Generate histogram + density + normal curve do.call(hist, c(list(var, prob = TRUE), hist_params)) do.call(lines, c(list(var_density), lines.)) do.call(curve, c(list(substitute(dnorm(x, mean=mean(var), sd=sd(var))), add = TRUE), curve.)) # Generate QQ plot + QQ line do.call(qqnorm, c(list(var), qqnorm.)) do.call(qqline, c(list(var), qqline.)) } # Plot original variable plot_single_norm(z, zname) # Plot log2-transformed variable plot_single_norm(z_log2, z_log2_label) }
Key Improvements:
- Safety Check: Blocks log2 transformation for variables with non-positive values to avoid runtime errors.
- Code Reusability: Added a
plot_single_norm()helper function to eliminate duplicate code for original and transformed variables. - Auto-Labeling: Automatically creates descriptive titles/labels for the log2-transformed variable (e.g.,
log2(Sepal.Length)for your iris example). - 2×2 Layout: Adjusted
par(mfrow=c(2,2))to fit all four plots neatly.
Example Usage:
# Test with iris dataset's Sepal.Length (all values are positive, so log2 works) norm_f(iris$Sepal.Length)
This will produce:
- Top-left: Histogram + density curve + normal curve for original
Sepal.Length - Top-right: QQ plot for original
Sepal.Length - Bottom-left: Histogram + density curve + normal curve for
log2(Sepal.Length) - Bottom-right: QQ plot for
log2(Sepal.Length)
内容的提问来源于stack exchange,提问作者cmirian
相关产品推荐
相关产品推荐

