# ============================================================
# 09_visualization.R —— 论文级图表规范（对应教程第 14 章）
# 用法：Rscript code/09_visualization.R（或 RStudio 逐段运行）
# 目标：统一主题、中文字体、300 dpi 导出
# ============================================================

library(Seurat)
library(ggplot2)
library(showtext)
library(patchwork)

## 1. 中文字体（Windows：微软雅黑/黑体；macOS：PingFang；Linux：Noto）
font_add("yahei", "msyh.ttc")          # 路径可按系统调整
showtext_auto()

## 2. 统一定制主题（论文风：无网格、合适字号、色盲友好配色）
theme_pub <- theme_classic(base_size = 10) +
  theme(
    plot.title = element_text(face = "bold", size = 11, hjust = 0.5),
    axis.text = element_text(color = "black"),
    legend.key.size = unit(0.4, "cm"),
    panel.border = element_rect(color = "grey70", fill = NA, linewidth = 0.4)
  )
okabe_ito <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442",
               "#0072B2", "#D55E00", "#CC79A7", "#999999")

## 3. 读入注释后的对象
obj <- readRDS("data/processed/visium_niche.rds")

## 4. 论文风空间图
p_niche <- SpatialDimPlot(obj, group.by = "niche", label = FALSE) +
  scale_fill_manual(values = okabe_ito) +
  ggtitle("空间生态位") +
  theme_pub

## 5. 特征图（marker 空间分布）
p_marker <- SpatialFeaturePlot(obj, features = c("EPCAM", "CD3D"),
                               alpha = c(0.1, 1)) &
  theme_pub

## 6. 细胞类型构成（堆叠条形）
comp <- as.data.frame(table(obj$niche, obj$celltype))
colnames(comp) <- c("niche", "celltype", "n")
p_comp <- ggplot(comp, aes(x = niche, y = n, fill = celltype)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_fill_manual(values = okabe_ito) +
  labs(x = "生态位", y = "比例", fill = "细胞类型", title = "生态位细胞组成") +
  theme_pub + theme(axis.text.x = element_text(angle = 30, hjust = 1))

## 7. 拼图并导出（300 dpi，PNG + PDF 双份）
dir.create("figures/results", showWarnings = FALSE)
p_all <- (p_niche | p_marker) / p_comp
ggsave("figures/results/figure_main.png", p_all, width = 10, height = 8, dpi = 300)
ggsave("figures/results/figure_main.pdf", p_all, width = 10, height = 8)
cat("论文级图表已导出到 figures/results/\n")
