You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2绘图中调整显著性星号的大小?

解决ggplot2柱状图显著性星号尺寸过小的问题

问题背景

我希望基于padj值在ggplot2绘制的柱状图中添加显著性星号,但手动添加的星号尺寸过小,不知道如何放大。

数据框

df <- structure(list(CancerType = c("BRCA", "COAD", "LUAD", "LUSC", 
"STAD", "THCA", "UCEC", "ESCA", "KIRC", "PRAD", "LIHC", "GBM", 
"BLCA"), log2FC = c(-0.145366946, -0.276093973, 0.056591306, 
0.150671917, 0.159516768, 0.040044405, -0.050525831, -0.09909923, 
0.125670677, -0.131356051, 0.090115912, -0.170939552, -0.150633173
), padj = c(0.002552355, 0.001254905, 0.515358544, 0.119809051, 
0.117073154, 0.407311464, 0.595674904, 0.643894805, 0.029380174, 
0.014769961, 0.251602611, 0.470002204, 0.228163654)), class = "data.frame", row.names = c(7L, 
23L, 39L, 55L, 71L, 87L, 103L, 119L, 135L, 151L, 167L, 183L, 
199L))

原绘图代码

nudge <- 0.02
df |> 
  mutate(
    sig_label = case_when(
      padj < 0.001 ~ "***",
      padj < 0.01 ~ "**",
      padj <= 0.05 ~ "*",
      padj > 0.05 ~ ""
    ),
    label_position = ifelse(log2FC > 0, log2FC + nudge, log2FC - (nudge+0.01))
  ) |> ggplot(aes(x = CancerType,y = log2FC))+
  geom_bar(position="stack", stat="identity", fill='#38357A')+
  theme_bw()+
  theme(axis.text.x = element_text(size = 8, angle = 45, hjust = 1, colour = 'black'))+
  geom_text(aes(label = sig_label, y = label_position))

解决方案

要放大显著性星号,只需在geom_text()中添加size参数自定义星号的字体大小即可。同时可以优化代码,避免空标签占位,提升绘图效率。

修改后的完整代码:

nudge <- 0.02
df |> 
  mutate(
    sig_label = case_when(
      padj < 0.001 ~ "***",
      padj < 0.01 ~ "**",
      padj <= 0.05 ~ "*",
      TRUE ~ NA_character_  # 用NA替代空字符串,方便过滤无意义标签
    ),
    label_position = ifelse(log2FC > 0, log2FC + nudge, log2FC - (nudge+0.01))
  ) |> ggplot(aes(x = CancerType,y = log2FC))+
  geom_bar(position="stack", stat="identity", fill='#38357A')+
  theme_bw()+
  theme(axis.text.x = element_text(size = 8, angle = 45, hjust = 1, colour = 'black'))+
  geom_text(aes(label = sig_label, y = label_position), 
            size = 6,  # 自定义星号大小,可按需调整数值
            show.legend = FALSE,
            na.rm = TRUE)

说明:

  • size参数数值可灵活调整,数值越大星号显示越大;
  • 用NA_character_替代空字符串并配合na.rm=TRUE,能让ggplot跳过无意义的空标签绘制,减少资源消耗。

内容的提问来源于stack exchange,提问作者zahra abdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:50:30