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

如何为ggplot2图例添加不同字体/字号的标题与副标题

解决ggplot2图例多行文本不同字号的问题

要实现图例中多行文本的字号差异,默认的guide_legend无法直接完成,这里提供两种可行方案:

方法一:使用ggtext包(推荐)

ggtext支持在ggplot元素中解析Markdown/HTML格式,能轻松实现不同字号的文本效果:

  1. 先安装并加载ggtext包:
install.packages("ggtext")
library(ggtext)
  1. 修改原代码,将scale_size的name改成带HTML格式的文本,同时在theme中启用图例标题的Markdown解析:
gg <- ggplot(sig_table, aes(x = x, y = y, col = neg_log_FP)) +
  geom_point(aes(size = as.numeric(percentage))) +
  xlab("Cohort") +
  ylab("Signature") +
  scale_color_continuous(low = "blue", high = "red", name = "-log(pval)", limits = c(0,3)) +
  scale_size(
    name = "Size of circle<br><span style='font-size:8pt'>Proportion of<br>samples within<br>cohort</span>",
    limits = c(0,100), 
    range = c(0,12), 
    guide = guide_legend(override.aes=list(colour = "red"))
  ) +
  scale_x_discrete(limits = xlabels, position = "top") +
  scale_y_discrete(limits = ylabels) +
  theme_bw() +
  theme(legend.title = element_markdown()) # 关键设置:启用markdown解析

你可以根据需求调整<span>标签内的font-size数值(比如8pt、10pt)。

方法二:手动修改gtable(无需额外包)

如果不想安装新包,可通过gtable直接修改图例的文本属性:

  1. 先绘制图形并提取gtable对象:
gg <- ggplot(sig_table, aes(x = x, y = y, col = neg_log_FP)) +
  geom_point(aes(size = as.numeric(percentage))) +
  xlab("Cohort") +
  ylab("Signature") +
  scale_color_continuous(low = "blue", high = "red", name = "-log(pval)", limits = c(0,3)) +
  scale_size(
    name = "Size of circle\nProportion of\nsamples within\ncohort",
    limits = c(0,100), 
    range = c(0,12), 
    guide = guide_legend(override.aes=list(colour = "red"))
  ) +
  scale_x_discrete(limits = xlabels, position = "top") +
  scale_y_discrete(limits = ylabels) +
  theme_bw()

# 提取图形的gtable结构
gt <- ggplotGrob(gg)

# 定位图例标题的文本框(需根据图形布局调整索引,可通过gt$grobs查看结构)
legend_title <- gt$grobs[[which(sapply(gt$grobs, function(x) x$name) == "guide-box")]]$grobs[[1]]$grobs[[1]]

# 修改后三行文本的字号,第一行保持原大小,后三行设为8pt
legend_title$children[[1]]$gp$fontsize <- c(11, 8, 8, 8)

# 重新绘制调整后的图形
grid::grid.draw(gt)

注意:这种方法需要手动定位文本框索引,不同图形布局可能需要调整索引值,灵活性稍差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:20:56