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

ggplot2图例标题修改问题:如何将Enrichment_Score改为Enrichment Score

你的代码无法修改图例标题的核心问题是guides()函数中对颜色图例的调用参数错误:你在aes()中映射的是colour = Enrichment_score,且使用了scale_colour_gradientn定义连续颜色渐变,guides()中对应的控制参数应为colour,而非你写的scale_color_gradient。

另外补充两个可优化的细节:

  • aes()中不需要额外加数据框名前缀Practice$,ggplot会自动从传入的数据框中读取对应变量,冗余前缀可能导致映射异常
  • 你后续调用的theme_bw()会覆盖之前设置的legend.position="bottom",如果需要保留图例在底部的配置,需要将主题自定义项放在theme_bw()之后

可行修改方案(二选一即可)

方案1:直接在颜色标度函数中指定标题(更简洁)

D1 <- ggplot(Practice, aes(case, pathway, 
      colour = Enrichment_score, size = q.value)) +
  geom_point() +
  # 直接在颜色标度中添加name参数修改图例标题
  scale_colour_gradientn(colours = cols, name = "Enrichment Score") +
  scale_size(range = c(1,15), name = "FDR q value")

D1 + ggtitle("Gene Set Enrichment Treg cells") +
  xlab("Case") + 
  ylab("Hallmark Gene Sets") +
  theme_bw() +
  theme(legend.position="bottom")

方案2:修正guides()函数的参数

D1 <- ggplot(Practice, aes(case, pathway, 
      colour = Enrichment_score, size = q.value)) +
  geom_point() +
  scale_colour_gradientn(colours = cols) +
  scale_size(range = c(1,15)) +
  guides(size=guide_legend(title = "FDR q value"),
         # 把参数名改为colour和aes中的映射对应
         colour=guide_legend(title = "Enrichment Score"))

D1 + ggtitle("Gene Set Enrichment Treg cells") +
  xlab("Case") + 
  ylab("Hallmark Gene Sets") +
  theme_bw() +
  theme(legend.position="bottom")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:57:03