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

ggplot2实操技巧:如何移除坐标轴标签前缀“REACTOME_”

可行实现方案

方案1:在现有标签处理逻辑中新增前缀删除规则(无需修改原始数据)

直接在你当前scale_x_discrete的标签处理函数里叠加前缀匹配删除逻辑即可,只需要调整label参数的自定义函数,修改后代码如下:

scale_x_discrete(label = function(x) {
  # 先匹配删除开头的REACTOME_前缀,^用于限定仅匹配字符串开头的对应内容
  x <- stringr::str_remove(x, "^REACTOME_")
  # 再执行你原有设定的长度截断
  stringr::str_trunc(x, 40, "right")
})

方案2:提前预处理数据集的通路字段(适合后续多场景复用处理后的数据)

如果你后续所有用到该数据集的分析、绘图都不需要保留REACTOME_前缀,可以在绘图前的数据清洗阶段直接处理pathway列:

# 先完成数据过滤、前缀删除处理
plot_df <- fgseaResTidy %>% 
  filter(padj < 0.05) %>% 
  head(n= 20) %>% 
  mutate(pathway = stringr::str_remove(pathway, "^REACTOME_"))

# 绘图时直接调用处理好的数据即可
ggplot(plot_df, aes(reorder(pathway, NES), NES)) +
  geom_col(aes(fill= NES > 5)) +
  coord_flip() +
  labs(x="Pathway", y="Normalized Enrichment Score",
       title="Hallmark pathways NES from GSEA") + 
  theme(axis.text.y.left = element_text(size = 10)) +
  scale_x_discrete(label = function(x) stringr::str_trunc(x, 40, "right")) +
  theme_minimal()

补充:你原有代码中scale_x_discrete行末尾漏了连接theme_minimal()的+号,上述修正代码已经补全。


内容的提问来源于stack exchange,提问作者Naomi Croft Guslund

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:15:04