{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6771279f",
   "metadata": {},
   "source": [
    "---\n",
    "title: \"单细胞基因表达相关性散点图可视化\"\n",
    "author: SeekGene\n",
    "date: 2026-01-29\n",
    "tags:\n",
    "  - 3' 转录组\n",
    "  - 5' + 免疫组库\n",
    "  - ATAC + RNA 双组学\n",
    "  - FFPE 单细胞转录组\n",
    "  - Notebooks\n",
    "  - 全序列转录组\n",
    "  - 甲基化 + RNA 双组学\n",
    "  - 空间转录组\n",
    "  - 绘图\n",
    "---\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1c4b14f-64aa-40b2-8baa-4a9ad92759cd",
   "metadata": {
    "tags": []
   },
   "source": [
    "# 单细胞基因表达相关性散点图可视化"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "818dba09",
   "metadata": {},
   "source": [
    "## 环境配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29ebf119-bbe2-489d-92f8-8b5624d37a8f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 加载所需的R包\n",
    "library(Seurat)      # 用于单细胞数据分析\n",
    "library(ggplot2)     # 用于数据可视化\n",
    "library(ggpubr)      # 用于添加统计信息到图形\n",
    "library(ggExtra)     # 用于添加边缘分布图\n",
    "library(dplyr)       # 用于数据处理和管道操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd30924c",
   "metadata": {},
   "source": [
    "## 数据读取与预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8bc345c-bc6c-4833-84e2-4148baddd1ff",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 读取数据和预处理\n",
    "seurat.obj <- readRDS(\"data/AY1739512568405/input.rds\")  # 读取Seurat对象\n",
    "meta <- read.table(\"data/AY1739512568405/meta.tsv\", header=T, sep=\"\\t\", row.names = 1)  # 读取元数据\n",
    "obj <- AddMetaData(seurat.obj, meta)  # 将元数据添加到Seurat对象\n",
    "DefaultAssay(obj) = \"RNA\"  # 设置默认分析数据为RNA表达数据\n",
    "head(obj@meta.data)  # 查看元数据的前几行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85f896c4-353c-4546-8fe2-a5b159521167",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 查看样本和细胞类型信息\n",
    "unique(obj@meta.data$Sample)  # 查看所有唯一的样本名\n",
    "unique(obj@meta.data$celltype)  # 查看所有唯一的细胞类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d15a4ff4-8e88-4a7c-87a4-dac53790a0f6",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 设置目标细胞类型和样本\n",
    "target_celltypes <- c('T cell')  # 指定目标细胞类型为T细胞\n",
    "target_samples1 <- c('S133T')    # 指定单个目标样本\n",
    "# 创建子集对象\n",
    "sub_obj1 <- subset(obj, subset = Sample %in% target_samples1 & celltype %in% target_celltypes)  # 创建单样本T细胞子集\n",
    "sub_obj2 <- subset(obj, subset = celltype %in% target_celltypes)  # 创建所有样本T细胞子集\n",
    "\n",
    "# 验证子集数据\n",
    "unique(sub_obj1@meta.data$Sample)    # 检查子集1的样本\n",
    "unique(sub_obj1@meta.data$celltype)  # 检查子集1的细胞类型\n",
    "unique(sub_obj2@meta.data$Sample)    # 检查子集2的样本\n",
    "unique(sub_obj2@meta.data$celltype)  # 检查子集2的细胞类型"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fd253b6",
   "metadata": {},
   "source": [
    "## 单样本相关性分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a993882-f4a3-422a-a027-08d9334606ed",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 提取单样本的基因表达数据\n",
    "plot_data1 <- FetchData(sub_obj1, \n",
    "                      vars = c(\"PPT1\", \"TRAF1\"),\n",
    "                      slot = \"data\")  # 从标准化数据中提取PPT1和TRAF1的表达值\n",
    "\n",
    "# 数据质量检查\n",
    "print(\"数据概要：\")\n",
    "summary(plot_data1)  # 显示数据的统计摘要\n",
    "print(\"NA值数量：\")\n",
    "print(colSums(is.na(plot_data1)))  # 检查NA值的数量\n",
    "print(\"0值数量：\")\n",
    "print(colSums(plot_data1 == 0))  # 检查0值的数量\n",
    "print(\"两个基因都为0的细胞数：\")\n",
    "sum(plot_data1$PPT1== 0 & plot_data1$TRAF1 == 0)  # 检查双零表达的细胞数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "999ccbd7-d9f8-45ac-9c6b-7ece9d0d9afe",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 过滤数据\n",
    "plot_data1_filtered <- plot_data1[plot_data1$PPT1 > 0 & plot_data1$TRAF1 > 0, ]  # 筛选双基因表达细胞\n",
    "print(\"筛选后的数据概要：\")\n",
    "summary(plot_data1_filtered)  # 显示筛选后的统计摘要\n",
    "print(paste0(\"筛选后的细胞数：\", nrow(plot_data1_filtered)))  # 显示筛选后的细胞数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "076802b0-4df1-40b3-98bf-de2259891136",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 创建单样本相关性散点图\n",
    "options(repr.plot.height=8, repr.plot.width=8)  # 设置图形大小\n",
    "p1 <- ggplot(plot_data1, aes(x = PPT1, y = TRAF1)) +\n",
    "    geom_point(size = 1, alpha = 0.5, color = \"grey30\") +  # 添加散点\n",
    "    geom_smooth(method = \"lm\", color = \"blue\", se = TRUE, fill = \"grey90\") +  # 添加拟合线\n",
    "    labs(x = \"PPT1 expression\", y = \"TRAF1 expression\") +  # 设置轴标签\n",
    "    theme_bw() +  # 设置主题\n",
    "    # 自定义主题细节\n",
    "    theme(\n",
    "        panel.grid.major = element_line(color = \"grey90\", linewidth = 0.3),\n",
    "        panel.grid.minor = element_line(color = \"grey90\", linewidth = 0.3),\n",
    "        panel.background = element_rect(fill = \"white\"),\n",
    "        panel.border = element_rect(color = \"black\", fill = NA, linewidth = 0.5),\n",
    "        axis.ticks = element_line(color = \"black\", linewidth = 0.3),\n",
    "        axis.text = element_text(color = \"black\", size = 10),\n",
    "        axis.title = element_text(color = \"black\", size = 16),\n",
    "        axis.ticks.length = unit(0.2, \"cm\"),\n",
    "        plot.background = element_rect(fill = \"white\")\n",
    "    ) +\n",
    "    # 设置x轴刻度\n",
    "    scale_x_continuous(\n",
    "        breaks = seq(0, max(plot_data1$PPT1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data1$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 设置y轴刻度\n",
    "    scale_y_continuous(\n",
    "        limits = c(0, max(plot_data1$TRAF1)),\n",
    "        breaks = seq(0, max(plot_data1$TRAF1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data1$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 添加相关性统计信息\n",
    "    stat_cor(method = \"pearson\",\n",
    "             label.x.npc = \"left\",\n",
    "             label.y.npc = \"top\",\n",
    "             size = 4)\n",
    "# 添加边缘分布图\n",
    "p1_with_marginal <- ggMarginal(p1,\n",
    "                             type = \"density\",  # 设置边缘图类型为密度图\n",
    "                             margins = \"both\",  # 同时显示x和y轴的边缘分布\n",
    "                             size = 5,\n",
    "                             xparams = list(fill = \"orange\", alpha = 1),  # 设置x轴边缘图样式\n",
    "                             yparams = list(fill = \"blue\", alpha = 1))    # 设置y轴边缘图样式\n",
    "p1_with_marginal  # 显示图形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6932067d-d495-4703-b28a-ac9ad144fa11",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 创建过滤后数据的散点图\n",
    "options(repr.plot.height=8, repr.plot.width=8)  # 设置图形大小\n",
    "p1_filtered <- ggplot(plot_data1_filtered, aes(x = PPT1, y = TRAF1)) +\n",
    "    geom_point(size = 1, alpha = 0.5, color = \"grey30\") +  # 添加散点\n",
    "    geom_smooth(method = \"lm\", color = \"blue\", se = TRUE, fill = \"grey90\") +  # 添加拟合线和置信区间\n",
    "    labs(x = \"PPT1 expression\", y = \"TRAF1 expression\") +  # 设置轴标签\n",
    "    # 设置主题和样式\n",
    "    theme_bw() +\n",
    "    theme(\n",
    "        panel.grid.major = element_line(color = \"grey90\", linewidth = 0.3),  # 主网格线\n",
    "        panel.grid.minor = element_line(color = \"grey90\", linewidth = 0.3),  # 次网格线\n",
    "        panel.background = element_rect(fill = \"white\"),  # 背景颜色\n",
    "        panel.border = element_rect(color = \"black\", fill = NA, linewidth = 0.5),  # 边框\n",
    "        axis.ticks = element_line(color = \"black\", linewidth = 0.3),  # 刻度线\n",
    "        axis.text = element_text(color = \"black\", size = 10),  # 轴文本\n",
    "        axis.title = element_text(color = \"black\", size = 16),  # 轴标题\n",
    "        axis.ticks.length = unit(0.2, \"cm\"),  # 刻度线长度\n",
    "        plot.background = element_rect(fill = \"white\")  # 图形背景\n",
    "    ) +\n",
    "    # 设置x轴刻度\n",
    "    scale_x_continuous(\n",
    "        breaks = seq(0, max(plot_data1_filtered$PPT1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data1_filtered$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 设置y轴刻度\n",
    "    scale_y_continuous(\n",
    "        limits = c(0, max(plot_data1_filtered$TRAF1)),\n",
    "        breaks = seq(0, max(plot_data1_filtered$TRAF1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data1_filtered$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 添加相关性统计信息\n",
    "    stat_cor(method = \"pearson\",\n",
    "             label.x.npc = \"left\",\n",
    "             label.y.npc = \"top\",\n",
    "             size = 4)\n",
    "\n",
    "# 为过滤后的散点图添加边缘分布图\n",
    "p1_filtered_with_marginal <- ggMarginal(p1_filtered,\n",
    "                             type = \"density\",  # 设置边缘图类型为密度图\n",
    "                             margins = \"both\",  # 显示两个轴的边缘分布\n",
    "                             size = 5,\n",
    "                             xparams = list(fill = \"orange\", alpha = 1),  # x轴边缘图样式\n",
    "                             yparams = list(fill = \"blue\", alpha = 1))    # y轴边缘图样式\n",
    "p1_filtered_with_marginal  # 显示图形"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce9ca162-c1d1-4917-90ea-f039ddebb61f",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 图片说明\n",
    "\n",
    "这是一个基因表达相关性散点图，展示了 PPT1 和 TRAF1 这两个基因在细胞中表达水平的关系：\n",
    "\n",
    "**(1) 主图部分**\n",
    "*   **X轴**：代表 PPT1 基因的表达水平\n",
    "*   **Y轴**：代表 TRAF1 基因的表达水平\n",
    "*   **点**：每个灰色点代表一个细胞\n",
    "*   **拟合线**：蓝色线是拟合线，表示两个基因表达的总体趋势\n",
    "*   **置信区间**：浅灰色区域是拟合线的置信区间\n",
    "\n",
    "**(2) 图中的统计信息**\n",
    "*   **R = 0.72**：表示相关系数，范围在 -1 到 1 之间。0.72 表示这两个基因有较强的正相关关系\n",
    "*   **p = 2.5e-16**：p 值极小，说明这种相关性具有统计学显著性\n",
    "\n",
    "**(3) 边缘分布图**\n",
    "*   **上方橙色曲线**：显示 PPT1 表达量的分布\n",
    "*   **右侧蓝色曲线**：显示 TRAF1 表达量的分布\n",
    "\n",
    "**生物学意义**\n",
    "PPT1 和 TRAF1 的表达呈现显著的正相关，即当一个基因表达量增加时，另一个基因的表达量也倾向于增加。这种相关性可能暗示这两个基因在细胞中可能有功能上的联系或者受到类似的调控机制。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96b75cce",
   "metadata": {},
   "source": [
    "## 多样本相关性分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9bf08a3-f1e9-4470-b5d5-b9bd7ab40bd7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 提取多样本表达数据和分组信息\n",
    "plot_data2 <- FetchData(sub_obj2, \n",
    "                      vars = c(\"PPT1\", \"TRAF1\", \"Sample\"),  # 提取基因表达值和样本信息\n",
    "                      slot = \"data\")  # 使用标准化数据\n",
    "\n",
    "# 数据质量检查\n",
    "print(\"数据概要：\")\n",
    "summary(plot_data2)  # 显示数据概要\n",
    "print(\"NA值数量：\")\n",
    "print(colSums(is.na(plot_data2)))  # 检查NA值\n",
    "print(\"0值数量：\")\n",
    "print(colSums(plot_data2 == 0))  # 检查0值\n",
    "print(\"两个基因都为0的细胞数：\")\n",
    "sum(plot_data2$PPT1== 0 & plot_data2$TRAF1 == 0)  # 检查双零表达细胞"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3231ab57-0d20-4490-8e47-061a5d53ef2d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 过滤多样本数据\n",
    "plot_data2_filtered <- plot_data2[plot_data2$PPT1 > 0 & plot_data2$TRAF1 > 0, ]  # 筛选双基因表达细胞\n",
    "print(\"筛选后的数据概要：\")\n",
    "summary(plot_data2_filtered)  # 显示筛选后的统计摘要\n",
    "print(paste0(\"筛选后的细胞数：\", nrow(plot_data2_filtered)))  # 显示筛选后的细胞数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc3351f0-e40c-4bf3-9bcb-c06b25aa3854",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 创建多样本散点图\n",
    "options(repr.plot.height=8, repr.plot.width=8)  # 设置图形大小\n",
    "p2 <- ggplot(plot_data2, aes(x = PPT1, y = TRAF1, color = Sample)) +  # 按样本着色\n",
    "    geom_point(size = 1.5, alpha = 0.8) +  # 添加散点\n",
    "    labs(title = \"PPT1 vs TRAF1 Correlation\",  # 设置标题\n",
    "         x = \"PPT1 expression\",  # x轴标签\n",
    "         y = \"TRAF1 expression\") +  # y轴标签\n",
    "    # 设置主题和样式\n",
    "    theme_bw() +\n",
    "    theme(\n",
    "        panel.grid.major = element_line(color = \"grey90\", linewidth = 0.3),  # 主网格线\n",
    "        panel.grid.minor = element_line(color = \"grey95\", linewidth = 0.3),  # 次网格线\n",
    "        panel.background = element_rect(fill = \"white\"),  # 背景\n",
    "        panel.border = element_rect(color = \"black\", fill = NA, linewidth = 0.5),  # 边框\n",
    "        axis.ticks = element_line(color = \"black\", linewidth = 0.3),  # 刻度线\n",
    "        axis.text = element_text(color = \"black\", size = 16),  # 轴文本\n",
    "        axis.title = element_text(color = \"black\", size = 16),  # 轴标题\n",
    "        legend.title = element_text(size = 16),  # 图例标题\n",
    "        legend.text = element_text(size = 16),  # 图例文本\n",
    "        legend.position = \"right\",  # 图例位置\n",
    "        plot.title = element_text(size = 16, hjust = 0)  # 图标题\n",
    "    ) +\n",
    "    # 设置x轴刻度\n",
    "    scale_x_continuous(\n",
    "        breaks = seq(0, max(plot_data2$PPT1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data2$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 设置y轴刻度\n",
    "    scale_y_continuous(\n",
    "        limits = c(0, max(plot_data2$TRAF1)),\n",
    "        breaks = seq(0, max(plot_data2$TRAF1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data2$TRAF1), by = 0.5)\n",
    "    )\n",
    "p2  # 显示图形"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c580678-de8a-4004-9d56-dd5a738d8fc3",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 图片说明\n",
    "\n",
    "这是一个多样本的基因表达相关性散点图，展示了不同样本中 PPT1 和 TRAF1 两个基因的表达关系（具体每个样本中两基因的相关性系数和 P 值可以从下面输出的 correlation_results.txt 中看到）：\n",
    "\n",
    "**(1) 图的基本结构**\n",
    "*   **X轴**：PPT1 基因的表达水平\n",
    "*   **Y轴**：TRAF1 基因的表达水平\n",
    "*   **图例**：右侧图例，不同颜色代表不同的样本（S133A 到 S159T，以 \"A\" 结尾的为癌旁样本，以 \"T\" 结尾的为肿瘤样本）\n",
    "*   **点**：每个点代表一个细胞\n",
    "\n",
    "**(2) 数据特征**\n",
    "*   可以看到多个样本中都存在 PPT1 和 TRAF1 的正相关趋势\n",
    "*   在 X 轴和 Y 轴接近 0 的位置有较多的点，表示有些细胞这两个基因的表达量都很低\n",
    "*   不同样本的相关性模式可能略有不同\n",
    "\n",
    "**生物学意义**\n",
    "*   可以比较不同样本（尤其是肿瘤和癌旁）中这两个基因的表达关系差异\n",
    "*   有助于理解这两个基因在不同病理状态下的表达调控关系\n",
    "*   可能发现潜在的样本特异性表达模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20f8369a-6318-4c92-a32d-af830b9fb069",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 计算每个样本的相关性统计\n",
    "correlation_results <- plot_data2 %>%\n",
    "  group_by(Sample) %>%  # 按样本分组\n",
    "  summarise(\n",
    "    Correlation = cor(PPT1, TRAF1, method = \"pearson\"),  # 计算Pearson相关系数\n",
    "    P_value = cor.test(PPT1, TRAF1, method = \"pearson\")$p.value,  # 计算p值\n",
    "    Sample_size = n()  # 计算样本量\n",
    "  ) %>%\n",
    "  mutate(\n",
    "    P_value = format(P_value, scientific = TRUE, digits = 3)  # 格式化p值为科学计数法\n",
    "  )\n",
    "\n",
    "# 保存相关性结果\n",
    "write.table(correlation_results, \n",
    "            file = \"Tcell_allsampes_PPT1_TRAF1_correlation_results.txt\", \n",
    "            sep = \"\\t\",             # tab分隔\n",
    "            row.names = FALSE,      # 不包含行名\n",
    "            quote = FALSE)          # 不加引号"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcd128a2-e8f0-480b-8911-c45b278ce872",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 创建过滤后的多样本散点图\n",
    "options(repr.plot.height=8, repr.plot.width=8)  # 设置图形大小\n",
    "p2_filtered <- ggplot(plot_data2_filtered, aes(x = PPT1, y = TRAF1, color = Sample)) +  # 按样本着色\n",
    "    geom_point(size = 1.5, alpha = 0.8) +  # 添加散点\n",
    "    labs(title = \"PPT1 vs TRAF1 Correlation\",  # 设置标题\n",
    "         x = \"PPT1 expression\",  # x轴标签\n",
    "         y = \"TRAF1 expression\") +  # y轴标签\n",
    "    # 设置主题和样式\n",
    "    theme_bw() +\n",
    "    theme(\n",
    "        panel.grid.major = element_line(color = \"grey90\", linewidth = 0.3),  # 主网格线\n",
    "        panel.grid.minor = element_line(color = \"grey95\", linewidth = 0.3),  # 次网格线\n",
    "        panel.background = element_rect(fill = \"white\"),  # 背景\n",
    "        panel.border = element_rect(color = \"black\", fill = NA, linewidth = 0.5),  # 边框\n",
    "        axis.ticks = element_line(color = \"black\", linewidth = 0.3),# 刻度线\n",
    "        axis.text = element_text(color = \"black\", size = 16),  # 轴文本\n",
    "        axis.title = element_text(color = \"black\", size = 16),  # 轴标题\n",
    "        legend.title = element_text(size = 16),  # 图例标题\n",
    "        legend.text = element_text(size = 16),  # 图例样本\n",
    "        legend.position = \"right\",  # 图例位置\n",
    "        plot.title = element_text(size = 16, hjust = 0)  # 图标题\n",
    "    ) +\n",
    "    # 设置x轴刻度\n",
    "    scale_x_continuous(\n",
    "        breaks = seq(0, max(plot_data2_filtered$PPT1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data2_filtered$TRAF1), by = 0.5)\n",
    "    ) +\n",
    "    # 设置y轴刻度\n",
    "    scale_y_continuous(\n",
    "        limits = c(0, max(plot_data2_filtered$TRAF1)),\n",
    "        breaks = seq(0, max(plot_data2_filtered$TRAF1), by = 1),\n",
    "        minor_breaks = seq(0, max(plot_data2_filtered$TRAF1), by = 0.5)\n",
    "    )\n",
    "p2_filtered  # 显示图形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d14036e-eff3-47ea-ba34-f6c13565a7a0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 计算过滤后每个样本的相关性统计\n",
    "correlation_results_filtered <- plot_data2_filtered %>%\n",
    "  group_by(Sample) %>%  # 按样本分组\n",
    "  summarise(\n",
    "    Correlation = cor(PPT1, TRAF1, method = \"pearson\"),  # 计算Pearson相关系数\n",
    "    # 计算p值\n",
    "    P_value = cor.test(PPT1, TRAF1, method = \"pearson\")$p.value,  # 计算p值\n",
    "    Sample_size = n()  # 计算样本量\n",
    "  ) %>%\n",
    "  # 将数值转换为科学计数法\n",
    "  mutate(\n",
    "    P_value = format(P_value, scientific = TRUE, digits = 3)\n",
    "  )\n",
    "\n",
    "# 保存相关性结果\n",
    "write.table(correlation_results_filtered,  # 格式化p值为科学计数法 \n",
    "            file = \"Tcell_allsampes_PPT1_TRAF1_filtered_correlation_results.txt\", \n",
    "            sep = \"\\t\",             # 使用tab分隔\n",
    "            row.names = FALSE,      # 不包含行名\n",
    "            quote = FALSE)          # 不给字符串加引号"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7990a4b9",
   "metadata": {},
   "source": [
    "## 结果保存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2eb7e269-8f7c-4220-9b70-c57cb0f5cc4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 保存图形\n",
    "ggsave(\"Tcell_S133T_PPT1_TRAF1_filtered_correlation_with_marginal.pdf\", \n",
    "       plot = p1_filtered_with_marginal, width = 8, height = 8)  # 保存单样本过滤后的图\n",
    "ggsave(\"Tcell_allsamples_PPT1_TRAF1_correlation.pdf\", \n",
    "       plot = p2, width = 8, height = 8)  # 保存多样本原始图\n",
    "ggsave(\"Tcell_allsamples_PPT1_TRAF1_filtered_correlation.pdf\", \n",
    "       plot = p2_filtered, width = 8, height = 8)  # 保存多样本过滤后的图"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "copyKAT",
   "language": "R",
   "name": "copykat"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "4.4.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
