BioF3 FigCode · SCI 绘图代码集

LASSO 系数条形图(LASSO Coefficient Barplot)

导出日期:2026年6月27日

分类:生存分析 | 依赖包:ggplot2、glmnet、survival

解决的生物学问题

哪些基因被 LASSO 选入 signature?它们是促进还是抑制预后?

应用场景

输入数据格式

数据框:gene, coefficient(从 cv.glmnet 提取非零系数)

关键参数

快速开始

1. 直接在线运行

打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。

2. 本地复现

下载脚本和示例数据,本地 RStudio 运行:

# 下载
curl -O https://<your-site>/figcode/scripts/lasso-coef.R
curl -O https://<your-site>/figcode/data/lasso-coef.csv

3. 安装依赖

# CRAN 包
install.packages(c("ggplot2", "glmnet", "survival"))

# Bioconductor 包(如需)
# BiocManager::install(c())

完整代码

library(ggplot2)
library(glmnet)
library(survival)

# --- Demo data ---
set.seed(42)
n <- 200; p <- 50
x <- matrix(rnorm(n * p), n, p)
colnames(x) <- paste0("Gene", 1:p)
time <- rexp(n, 0.05) * exp(-0.5 * x[,1] + 0.4 * x[,2] - 0.3 * x[,3])
event <- rbinom(n, 1, 0.7)
y <- Surv(time, event)

cv_fit <- cv.glmnet(x, y, family = "cox", alpha = 1, nfolds = 10)
coef_vec <- as.numeric(coef(cv_fit, s = "lambda.min"))
names(coef_vec) <- colnames(x)
selected <- coef_vec[coef_vec != 0]

# --- Plot ---
df <- data.frame(gene = names(selected), coef = selected)
df$direction <- ifelse(df$coef > 0, "Risk", "Protective")
df <- df[order(df$coef), ]
df$gene <- factor(df$gene, levels = df$gene)

ggplot(df, aes(x = gene, y = coef, fill = direction)) +
  geom_col(width = 0.7) +
  coord_flip() +
  scale_fill_manual(values = c(Risk = "#dc2626", Protective = "#2563eb")) +
  labs(x = NULL, y = "LASSO Coefficient", title = "Signature Gene Coefficients",
       fill = "Direction") +
  theme_classic() +
  theme(axis.text.y = element_text(size = 9))

替换为自己的数据

脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:

延伸阅读