# 1. Buat data distribusi normal (mu = 0, sigma = 1)
mu <- 10
sigma <- 2
x <- seq(mu - 4*sigma, mu + 4*sigma, length.out = 1000)
y <- dnorm(x, mean = mu, sd = sigma)

# 2. Plot kurva utama
plot(x, y, type = "l", lwd = 2.5, col = "#1f77b4",
     main = "Kurva Distribusi Normal Standar",
     xlab = "Nilai (Z-score)", 
     ylab = "Kerapatan Probabilitas",
     las = 1)

# 3. Arsir area ±2 SD (95,4%)
polygon(c(-2, x[x >= -2 & x <= 2], 2), 
        c(0, y[x >= -2 & x <= 2], 0), 
        col = rgb(0.12, 0.47, 0.71, alpha = 0.15), border = NA)

# 4. Arsir area ±1 SD (68,2%)
polygon(c(-1, x[x >= -1 & x <= 1], 1), 
        c(0, y[x >= -1 & x <= 1], 0), 
        col = rgb(0.12, 0.47, 0.71, alpha = 0.3), border = NA)

# 5. Tambahkan garis tengah (Mean) dan grid
abline(v = mu, col = "red", lty = 2, lwd = 1.5)
grid(col = "lightgray", lty = "dotted")

# 6. Tambahkan legenda
legend("topright", 
       legend = c("mu = 10, sigma = 2", "68,2% (+/- 1SD)", "95,4% (+/- 2SD)", "Mean (mu)"),
       col = c("#1f77b4", rgb(0.12, 0.47, 0.71, 0.3), rgb(0.12, 0.47, 0.71, 0.15), "red"),
       lty = c(1, 1, 1, 2), 
       lwd = c(2.5, 6, 6, 1.5), 
       bty = "n")

# ---------------------------------------------------------------
# 1. MENGGUNAKAN BASE R (Membuat 4 Grafik dalam 1 Grid)
# ---------------------------------------------------------------

# Mengatur tata letak grid 2x2
par(mfrow = c(2, 2), mar = c(4, 4, 3, 1))

# Data sampel
set.seed(123)
kategori <- c("A", "B", "C", "D")
nilai <- c(23, 45, 12, 36)
x_data <- rnorm(100, mean = 50, sd = 10)
y_data <- 2 * x_data + rnorm(100, mean = 0, sd = 10)

# Grafik 1: Diagram Batang (Barplot)
barplot(nilai, names.arg = kategori, col = "#3498db",
        main = "1. Diagram Batang", xlab = "Kategori", ylab = "Nilai")

# Grafik 2: Diagram Lingkaran (Pie Chart)
pie(nilai, labels = kategori, col = rainbow(4),
    main = "2. Diagram Lingkaran")

# Grafik 3: Histogram Distribusi
hist(x_data, col = "#2ecc71", border = "white",
     main = "3. Histogram", xlab = "Variabel X", ylab = "Frekuensi")

# Grafik 4: Diagram Sebar (Scatter Plot)
plot(x_data, y_data, col = "#e74c3c", pch = 16,
     main = "4. Scatter Plot", xlab = "X", ylab = "Y")

# Mengembalikan pengaturan tata letak ke default
par(mfrow = c(1, 1))
# Parameter
mu <- 10
var1 <- 1; sd1 <- sqrt(var1)
var2 <- 2; sd2 <- sqrt(var2)

# Rentang sumbu X terfokus di sekitar mu = 10
x <- seq(mu - 4 * sd2, mu + 4 * sd2, length.out = 500)

y1 <- dnorm(x, mean = mu, sd = sd1)
y2 <- dnorm(x, mean = mu, sd = sd2)

# Plot Kurva 1
plot(x, y1, type = "l", col = "#1F77B4", lwd = 2.5,
     main = "Kurva Normal Bertumpuk pada Rata-Rata Sama (mu = 10)",
     xlab = "Nilai X", ylab = "Densitas",
     ylim = c(0, max(y1, y2)), las = 1, bty = "l")

# Area transparan Kurva 1
polygon(c(x, rev(x)), c(y1, rep(0, length(y1))), 
        col = rgb(0.12, 0.47, 0.71, 0.3), border = NA)

# Tambah Kurva 2
lines(x, y2, col = "#FF7F0E", lwd = 2.5)

# Area transparan Kurva 2
polygon(c(x, rev(x)), c(y2, rep(0, length(y2))), 
        col = rgb(1.0, 0.5, 0.05, 0.3), border = NA)

grid()
legend("topright", 
       legend = c(expression(N(10, 1)), expression(N(10, 2))),
       col = c("#1F77B4", "#FF7F0E"), lwd = 2.5, bty = "n")

# Parameter Kurva 1
mu1 <- 8; var1 <- 1; sd1 <- sqrt(var1)

# Parameter Kurva 2
mu2 <- 10; var2 <- 2; sd2 <- sqrt(var2)

# Rentang sumbu X mencakup kedua kurva
x <- seq(4, 15, length.out = 500)

y1 <- dnorm(x, mean = mu1, sd = sd1)
y2 <- dnorm(x, mean = mu2, sd = sd2)

# Plot Kurva 1
plot(x, y1, type = "l", col = "#1F77B4", lwd = 2.5,
     main = "Kurva Normal Bertumpuk dengan Mean Berbeda",
     xlab = "Nilai X", ylab = "Densitas",
     ylim = c(0, max(y1, y2)), las = 1, bty = "l")

# Area transparan Kurva 1
polygon(c(x, rev(x)), c(y1, rep(0, length(y1))), 
        col = rgb(0.12, 0.47, 0.71, 0.3), border = NA)

# Tambah Kurva 2
lines(x, y2, col = "#FF7F0E", lwd = 2.5)

# Area transparan Kurva 2
polygon(c(x, rev(x)), c(y2, rep(0, length(y2))), 
        col = rgb(1.0, 0.5, 0.05, 0.3), border = NA)

grid()
legend("topright", 
       legend = c(expression(N(8, 1)), expression(N(10, 2))),
       col = c("#1F77B4", "#FF7F0E"), lwd = 2.5, bty = "n")

# Parameter (mu dan sd)
params <- list(
  c(mu = 0,   sd = 2,   col = "pink"), # Biru
  c(mu = 2,   sd = 1,   col = "green"), # Hijau
  c(mu = 5,   sd = 5,   col = "red"), # Merah
  c(mu = 10,  sd = 3,   col = "purple"), # Ungu
  c(mu = 1.5, sd = 0.1, col = "orange")  # Oranye
)

# Rentang sumbu X
x <- seq(-11, 20, length.out = 2000)

# Plot Kurva 1 sebagai dasar
y1 <- dnorm(x, mean = 0, sd = 2)
plot(x, y1, type = "l", col = "blue", lwd = 2,
     main = "Perbandingan 5 Distribusi Normal Bertumpuk",
     xlab = "Nilai X", ylab = "Densitas",
     ylim = c(0, 4), # Membatasi sumbu Y agar kurva lain tetap terlihat jelas
     las = 1, bty = "l")

# Menambahkan kurva sisanya dengan perulangan (loop)
for (p in params) {
  m <- as.numeric(p["mu"])
  s <- as.numeric(p["sd"])
  cl <- p["col"]
  
  y <- dnorm(x, mean = m, sd = s)
  lines(x, y, col = cl, lwd = 2)
  polygon(c(x, rev(x)), c(y, rep(0, length(y))), 
          col = adjustcolor(cl, alpha.f = 0.15), border = NA)
}

grid()
legend("topright", 
       legend = c("N(0, sd=2)", "N(2, sd=1)", "N(5, sd=5)", "N(10, sd=3)", "N(1.5, sd=0.1)"),
       col = c("blue", "green", "red", "purple", "orange"), 
       lwd = 2, bty = "n")

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# 1. Definisikan parameter
dist_info <- data.frame(
  label = factor(
    c("1. N(0, sd=2)", "2. N(2, sd=1)", "3. N(5, sd=5)", "4. N(10, sd=3)", "5. N(1.5, sd=0.1)"),
    levels = c("1. N(0, sd=2)", "2. N(2, sd=1)", "3. N(5, sd=5)", "4. N(10, sd=3)", "5. N(1.5, sd=0.1)")
  ),
  mu = c(0, 2, 5, 10, 1.5),
  sd = c(2, 1, 5, 3, 0.1)
)

# 2. Bangkitkan titik-titik data untuk setiap panel
df_plot <- dist_info %>%
  rowwise() %>%
  do({
    x_vals <- seq(.$mu - 4 * .$sd, .$mu + 4 * .$sd, length.out = 300)
    y_vals <- dnorm(x_vals, mean = .$mu, sd = .$sd)
    data.frame(label = .$label, x = x_vals, y = y_vals)
  })

# 3. Plot terpisah dengan facet_wrap
ggplot(df_plot, aes(x = x, y = y, fill = label, color = label)) +
  geom_area(alpha = 0.25) +
  geom_line(linewidth = 1) +
  facet_wrap(~ label, scales = "free", ncol = 3) + # 'scales = free' menyesuaikan sumbu X & Y
  labs(title = "Visualisasi Terpisah 5 Distribusi Normal",
       x = "Nilai X", 
       y = "Densitas") +
  theme_minimal() +
  theme(legend.position = "none",
        strip.text = element_text(face = "bold", size = 10))

library(ggplot2)

# Rentang sumbu X
df_plot <- data.frame(x = c(-4, 4))

ggplot(df_plot, aes(x = x)) +
  # t-distribution df = 1 (Tebal di ekor / heavy-tailed)
  stat_function(fun = dt, args = list(df = 1),
                aes(color = "t (df = 1)"), linewidth = 1) +
  
  # t-distribution df = 5
  stat_function(fun = dt, args = list(df = 5),
                aes(color = "t (df = 5)"), linewidth = 1) +
  
  # t-distribution df = 30
  stat_function(fun = dt, args = list(df = 30),
                aes(color = "t (df = 30)"), linewidth = 1) +
  
  # Normal Standar N(0,1) sebagai pembanding (Garis Putus-Putus)
  stat_function(fun = dnorm, args = list(mean = 0, sd = 1),
                aes(color = "Normal Standar N(0,1)"), 
                linewidth = 1.2, linetype = "dashed") +
  
  # Skala Warna & Legenda
  scale_color_manual(name = "Distribusi", 
                     values = c("t (df = 1)" = "#D62728",    # Merah
                                "t (df = 5)" = "#FF7F0E",    # Oranye
                                "t (df = 30)" = "#2CA02C",   # Hijau
                                "Normal Standar N(0,1)" = "#1F77B4")) + # Biru
  
  labs(title = "Perbandingan Simultan Distribusi t-Student & Normal Standar",
       subtitle = "Makin besar df, distribusi t makin mendekati Normal Standar",
       x = "Nilai t / Z", 
       y = "Densitas") +
  theme_minimal() +
  theme(legend.position = "top")

library(ggplot2)
library(dplyr)

# 1. Menyiapkan data untuk masing-masing distribusi
df_norm <- data.frame(dist = "1. Distribusi Normal N(0, 1)", x = seq(-4, 4, length.out = 400)) %>%
  mutate(y = dnorm(x, mean = 0, sd = 1))

df_t <- data.frame(dist = "2. Distribusi t-Student (df = 3)", x = seq(-4, 4, length.out = 400)) %>%
  mutate(y = dt(x, df = 3))

df_ray <- data.frame(dist = "3. Distribusi Rayleigh R (scale = 2)", x = seq(0, 8, length.out = 400)) %>%
  mutate(y = (x / 2^2) * exp(-x^2 / (2 * 2^2)))

df_chisq <- data.frame(dist = "4. Distribusi Chi-Square (df = 4)", x = seq(0, 12, length.out = 400)) %>%
  mutate(y = dchisq(x, df = 4))

# 2. Penggabungan data
df_all <- bind_rows(df_norm, df_t, df_ray, df_chisq)

# 3. Plot terpisah dengan facet_wrap (Grid 2x2)
ggplot(df_all, aes(x = x, y = y, fill = dist, color = dist)) +
  geom_area(alpha = 0.25) +
  geom_line(linewidth = 1) +
  facet_wrap(~ dist, scales = "free", ncol = 2) +
  scale_color_manual(values = c("#1F77B4", "#FF7F0E", "#2CA02C", "#D62728")) +
  scale_fill_manual(values = c("#1F77B4", "#FF7F0E", "#2CA02C", "#D62728")) +
  labs(title = "Visualisasi Terpisah 4 Distribusi Statistika",
       x = "Nilai X", 
       y = "Densitas") +
  theme_minimal() +
  theme(legend.position = "none",
        strip.text = element_text(face = "bold", size = 10))

library(ggplot2)
library(dplyr)
if (!requireNamespace("statmod", quietly = TRUE)) install.packages("statmod")
library(statmod)

# Fungsi PDF Rayleigh & Pareto
drayleigh_custom <- function(x, scale) {
  ifelse(x < 0, 0, (x / scale^2) * exp(-x^2 / (2 * scale^2)))
}

dpareto_custom <- function(x, shape, scale) {
  ifelse(x < 0, 0, (shape / scale) * (1 + x / scale)^(-(shape + 1)))
}

# 1. Menyiapkan Grid X Seragam [-4, 8] untuk Semua Distribusi
# -------------------------------------------------------------
x_grid <- seq(-4, 8, length.out = 500)

df_all_stacked <- bind_rows(
  data.frame(dist = "t-Student (df = 3)", x = x_grid, y = dt(x_grid, df = 3)),
  data.frame(dist = "Rayleigh (scale = 2)", x = x_grid, y = drayleigh_custom(x_grid, scale = 2)),
  data.frame(dist = "Chi-Square (df = 4)", x = x_grid, y = dchisq(x_grid, df = 4)),
  data.frame(dist = "Gamma (shape = 2, rate = 1)", x = x_grid, y = dgamma(x_grid, shape = 2, rate = 1)),
  data.frame(dist = "Weibull (shape = 1.5, scale = 1)", x = x_grid, y = dweibull(x_grid, shape = 1.5, scale = 1)),
  data.frame(dist = "Eksponensial (rate = 0.8)", x = x_grid, y = dexp(x_grid, rate = 0.8)),
  data.frame(dist = "Pareto (shape = 3, scale = 1)", x = x_grid, y = dpareto_custom(x_grid, shape = 3, scale = 1)),
  data.frame(dist = "Uniform (min = 0, max = 5)", x = x_grid, y = dunif(x_grid, min = 0, max = 5)),
  data.frame(dist = "Inverse Gaussian (mean = 1, shape = 1)", x = x_grid, y = ifelse(x_grid <= 0, 0, dinvgauss(x_grid, mean = 1, shape = 1)))
)

# 2. Plot Menumpuk (Overlay)
# -------------------------------------------------------------
ggplot(df_all_stacked, aes(x = x, y = y, color = dist, fill = dist)) +
  geom_area(alpha = 0.12, position = "identity") +
  geom_line(linewidth = 0.95) +
  scale_x_continuous(breaks = seq(-4, 8, by = 2)) +
  coord_cartesian(ylim = c(0, 0.8)) +
  labs(
    title = "Perbandingan Menumpuk 9 Distribusi Probabilitas Kontinu",
    subtitle = "Diplot pada rentang sumbu X (-4 hingga 8) dan skala Y yang sama",
    x = "Nilai X",
    y = "Densitas",
    color = "Jenis Distribusi",
    fill = "Jenis Distribusi"
  ) +
  theme_minimal() +
  theme(
    legend.position = "right",
    legend.title = element_text(face = "bold", size = 10),
    legend.text = element_text(size = 8.5),
    plot.title = element_text(face = "bold", size = 13),
    panel.grid.minor = element_blank()
  )