如何为ggplot2图例添加不同字体/字号的标题与副标题
解决ggplot2图例多行文本不同字号的问题
要实现图例中多行文本的字号差异,默认的guide_legend无法直接完成,这里提供两种可行方案:
方法一:使用ggtext包(推荐)
ggtext支持在ggplot元素中解析Markdown/HTML格式,能轻松实现不同字号的文本效果:
- 先安装并加载ggtext包:
install.packages("ggtext") library(ggtext)
- 修改原代码,将
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直接修改图例的文本属性:
- 先绘制图形并提取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
相关产品推荐
相关产品推荐

