# 相关性热图：四项连续指标的 Pearson 相关
# 项目原创脚本，MIT 许可；模拟数据 CC0-1.0；图形 CC BY 4.0。
# 在全新 R 会话运行。每次运行会更新下方 output_dir 中的本示例文件。
# 图形标签使用英文以避免不同电脑缺少中文字体；可在参数和 labs() 中修改。

# 1. 依赖：首次使用时手动运行以下安装命令，脚本不会自动安装。
# install.packages(c("ggplot2", "jsonlite"))
required_packages <- c("ggplot2", "jsonlite")
missing_packages <- required_packages[!vapply(required_packages, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing_packages)) stop("Please install: ", paste(missing_packages, collapse = ", "))
library(ggplot2)

# 2. 可修改参数：颜色、字体、导出尺寸和路径。输出路径相对于当前工作目录。
set.seed(20261014)
colors <- c("#007F96", "#B66A46")
font_family <- "sans"
figure_width <- 8
figure_height <- 5.5
output_dir <- file.path(getwd(), "rfig-correlation-output")
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
theme_set(theme_minimal(base_size = 12, base_family = font_family) +
 theme(plot.background = element_rect(fill = "white", color = NA), panel.grid.minor = element_blank(),
       plot.title = element_text(face = "bold", size = 15), legend.position = "bottom",
       plot.margin = margin(14, 18, 14, 14)))

# 3. 示例数据：每行一位受试者，各列为连续指标。 选择需要比较的数值列，确认单位、异常值和缺失处理后重新计算。
# 使用自己的 CSV 时，将以下数据生成段替换为：
# data <- read.csv("your-data.csv", stringsAsFactors = FALSE)
# 再按本例要求设置分类顺序、检查字段、单位及缺失值。
latent <- rnorm(100)
data <- data.frame(marker_a = latent + rnorm(100, 0, .5), marker_b = .7 * latent + rnorm(100),
                   marker_c = -.6 * latent + rnorm(100), marker_d = rnorm(100))
stopifnot(!anyNA(data))
stopifnot(!anyNA(data))

# 4. 统计计算与绘图。使用 Pearson 相关，颜色范围固定为 −1 至 1。演示无缺失；脚本遇到缺失会停止，避免隐含改变样本量。未展示 P 值，相关性不表示一致性或因果关系。
correlation <- cor(data, method = "pearson", use = "everything")
long <- as.data.frame(as.table(correlation)); names(long) <- c("x", "y", "r")
p <- ggplot(long, aes(x, y, fill = r)) + geom_tile(color = "white", linewidth = 1) +
  geom_text(aes(label = sprintf("%.2f", r)), size = 4, color = "#183047") +
  scale_fill_gradient2(low = "#B66A46", mid = "#F5F7F9", high = "#087D92", limits = c(-1, 1), name = "Pearson r") +
  coord_equal() + labs(x = NULL, y = NULL, title = "Correlation of continuous measurements")
metrics <- list(r_ab = unname(correlation[1, 2]))
print(p)

# 5. 导出：CSV 与绘图所用 data 完全一致，preview 与科研图片均来自同一个 p。
write.csv(data, file.path(output_dir, "data.csv"), row.names = FALSE, fileEncoding = "UTF-8")
ggsave(file.path(output_dir, "preview.png"), p, width = figure_width, height = figure_height, dpi = 160, bg = "white")
ggsave(file.path(output_dir, "figure.png"), p, width = figure_width, height = figure_height, dpi = 300, bg = "white")
ggsave(file.path(output_dir, "figure.pdf"), p, width = figure_width, height = figure_height, device = grDevices::pdf, bg = "white")
ggsave(file.path(output_dir, "figure.tiff"), p, width = figure_width, height = figure_height, dpi = 300, compression = "lzw", bg = "white")
jsonlite::write_json(metrics, file.path(output_dir, "metrics.json"), auto_unbox = TRUE, digits = 16, pretty = TRUE)
