# Load ggplot2 for plotting
library(ggplot2)
# Define parameters
alpha <- 0.05 # Type I error rate
mu0 <- 0 # Mean under the null hypothesis
mu1 <- 2 # Mean under the alternative hypothesis
sigma <- 1 # Standard deviation
z_alpha <- qnorm(1 - alpha) # Critical z-score
# Create data frames for the null and alternative distributions
x <- seq(-4, 6, length.out = 1000)
h0_dist <- data.frame(x = x, y = dnorm(x, mean = mu0, sd = sigma))
h1_dist <- data.frame(x = x, y = dnorm(x, mean = mu1, sd = sigma))
# Plot the distributions
ggplot() +
geom_line(data = h0_dist, aes(x = x, y = y), color = "blue", size = 1) +
geom_line(data = h1_dist, aes(x = x, y = y), color = "red", size = 1) +
geom_vline(xintercept = z_alpha, linetype = "dashed", color = "purple") +
geom_area(data = subset(h0_dist, x > z_alpha), aes(x = x, y = y), fill = "blue", alpha = 0.3) +
geom_area(data = subset(h1_dist, x < z_alpha), aes(x = x, y = y), fill = "red", alpha = 0.3) +
labs(title = "Power of a Test and Error Types",
x = "Test Statistic",
y = "Density") +
annotate("text", x = z_alpha + 0.5, y = 0.05, label = "Type I Error", color = "blue") +
annotate("text", x = z_alpha - 1, y = 0.05, label = "Type II Error (Beta)", color = "red") +
theme_minimal()