{"spec_id":"line-pca-variance-cumulative","library":"ggplot2","language":"r","code":"#' anyplot.ai\n#' line-pca-variance-cumulative: Cumulative Explained Variance for PCA Component Selection\n#' Library: ggplot2 3.5.1 | R 4.4.1\n#' Quality: 88/100 | Created: 2026-05-29\n\nlibrary(ggplot2)\nlibrary(ragg)\n\nset.seed(42)\n\n# --- Theme tokens -----------------------------------------------------------\nTHEME       <- Sys.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG     <- if (THEME == \"light\") \"#FAF8F1\" else \"#1A1A17\"\nELEVATED_BG <- if (THEME == \"light\") \"#FFFDF6\" else \"#242420\"\nINK         <- if (THEME == \"light\") \"#1A1A17\" else \"#F0EFE8\"\nINK_SOFT    <- if (THEME == \"light\") \"#4A4A44\" else \"#B8B7B0\"\nINK_MUTED   <- if (THEME == \"light\") \"#6B6A63\" else \"#A8A79F\"\n\nIMPRINT_PALETTE <- c(\n  \"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\",\n  \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"\n)\n\n# --- Data -------------------------------------------------------------------\n# 300-sample × 15-feature sensor dataset driven by 3 latent factors,\n# giving a realistic PCA scree with a clear elbow around components 5-7\nn_obs      <- 300\nn_features <- 15\n\nf1 <- rnorm(n_obs)\nf2 <- rnorm(n_obs)\nf3 <- rnorm(n_obs)\n\nX <- matrix(0, nrow = n_obs, ncol = n_features)\nfor (i in 1:5)   X[, i] <- f1 * (1.8 - 0.25 * i) + rnorm(n_obs, 0, 0.3)\nfor (i in 6:10)  X[, i] <- f2 * (1.3 - 0.12 * (i - 5)) + rnorm(n_obs, 0, 0.4)\nfor (i in 11:15) X[, i] <- f3 * (0.9 - 0.08 * (i - 10)) + rnorm(n_obs, 0, 0.5)\n\npca      <- prcomp(X, center = TRUE, scale. = TRUE)\nvar_ind  <- pca$sdev^2 / sum(pca$sdev^2) * 100\nvar_cum  <- cumsum(var_ind)\n\ndf <- data.frame(\n  component      = seq_len(n_features),\n  individual_pct = var_ind,\n  cumulative_pct = var_cum\n)\n\nthr90 <- min(which(var_cum >= 90))\nthr95 <- min(which(var_cum >= 95))\n\n# Elbow detection: point of maximum perpendicular distance from line\n# connecting first and last cumulative-variance values\na_coef <- var_cum[n_features] - var_cum[1]\nb_coef <- -(n_features - 1)\nc_coef <- (n_features - 1) * var_cum[1] - (var_cum[n_features] - var_cum[1]) * 1\nknee_dist <- abs(a_coef * seq_len(n_features) + b_coef * var_cum + c_coef) /\n  sqrt(a_coef^2 + b_coef^2)\nelbow_pc <- which.max(knee_dist)\n\n# --- Plot -------------------------------------------------------------------\ntitle_str <- \"line-pca-variance-cumulative · r · ggplot2 · anyplot.ai\"\n\np <- ggplot(df, aes(x = component)) +\n  geom_col(aes(y = individual_pct),\n           fill = IMPRINT_PALETTE[1], alpha = 0.13, width = 0.65) +\n  geom_hline(yintercept = 90, linetype = \"dashed\",\n             color = INK_SOFT, linewidth = 0.55) +\n  geom_hline(yintercept = 95, linetype = \"dashed\",\n             color = INK_SOFT, linewidth = 0.55) +\n  geom_vline(xintercept = elbow_pc, linetype = \"dotted\",\n             color = IMPRINT_PALETTE[1], linewidth = 0.65, alpha = 0.55) +\n  geom_line(aes(y = cumulative_pct),\n            color = IMPRINT_PALETTE[1], linewidth = 1.2) +\n  geom_point(aes(y = cumulative_pct),\n             color = IMPRINT_PALETTE[1], size = 2.8) +\n  annotate(\"text\", x = 1.2, y = 91.8,\n           label = \"90%\", color = INK_MUTED, size = 3.3, hjust = 0) +\n  annotate(\"text\", x = 1.2, y = 96.8,\n           label = \"95%\", color = INK_MUTED, size = 3.3, hjust = 0) +\n  annotate(\"text\", x = thr90 + 0.3, y = 85,\n           label = sprintf(\"PC%d\\n90%%\", thr90),\n           color = INK_MUTED, size = 3.0, hjust = 0, lineheight = 0.9) +\n  annotate(\"text\", x = elbow_pc + 0.35, y = 5,\n           label = sprintf(\"PC%d\\nelbow\", elbow_pc),\n           color = IMPRINT_PALETTE[1], size = 3.3, hjust = 0, lineheight = 0.9) +\n  scale_x_continuous(breaks = seq_len(n_features)) +\n  scale_y_continuous(\n    limits = c(0, 105),\n    breaks = seq(0, 100, 20),\n    labels = function(x) paste0(x, \"%\")\n  ) +\n  labs(\n    x     = \"Number of Principal Components\",\n    y     = \"Cumulative Explained Variance\",\n    title = title_str\n  ) +\n  theme_minimal(base_size = 8) +\n  theme(\n    plot.background    = element_rect(fill = PAGE_BG, color = PAGE_BG),\n    panel.background   = element_rect(fill = PAGE_BG, color = NA),\n    panel.grid.major.y = element_line(color = INK, linewidth = 0.18),\n    panel.grid.major.x = element_blank(),\n    panel.grid.minor   = element_blank(),\n    panel.border       = element_blank(),\n    axis.line          = element_line(color = INK_SOFT, linewidth = 0.45),\n    axis.ticks         = element_blank(),\n    axis.title         = element_text(color = INK, size = 10),\n    axis.text          = element_text(color = INK_SOFT, size = 8),\n    plot.title         = element_text(color = INK, size = 12, face = \"bold\",\n                                      margin = margin(b = 14)),\n    plot.margin        = margin(22, 24, 18, 18)\n  )\n\n# --- Save -------------------------------------------------------------------\nggsave(\n  filename = sprintf(\"plot-%s.png\", THEME),\n  plot     = p,\n  device   = ragg::agg_png,\n  width    = 8,\n  height   = 4.5,\n  units    = \"in\",\n  dpi      = 400\n)\n"}