如何在ggplot2的annotate标注中对部分文本设置加粗效果
解决方案
ggplot2默认的annotate("text")不支持Markdown语法,你可以用以下两种方案实现局部加粗效果:
方案1:使用ggtext包实现Markdown语法支持(改动最小)
ggtext包支持直接解析Markdown格式的文本,你只需要调整标注类型为richtext,添加两个参数去掉默认的文本框样式即可。
如果还没有安装ggtext包,先运行安装命令:
install.packages("ggtext")
修改后的绘图代码:
library(tidyverse) library(ggtext) tibble(x= 1:100, y= 1:100) %>% ggplot(aes(x, y)) + scale_x_continuous(minor_breaks = seq(10, 100, 10)) + scale_y_continuous(minor_breaks = seq(10, 100, 10)) + geom_rect(xmin = 17, xmax=83, ymin=90, ymax=100, color='black', fill='#6d1d26', size=0.25) + annotate('richtext', x= 50, y=95, label= "**This sentence should be bold.** This sentence shouldn't", size=5, col = 'white', fill = NA, # 去掉文本框填充色 label.colour = NA) # 去掉文本框边框
方案2:使用原生plotmath语法(无需额外安装包)
如果你不想安装第三方包,可以用R内置的plotmath表达式,用bold()函数包裹需要加粗的内容,同时给annotate添加parse=TRUE参数即可:
library(tidyverse) tibble(x= 1:100, y= 1:100) %>% ggplot(aes(x, y)) + scale_x_continuous(minor_breaks = seq(10, 100, 10)) + scale_y_continuous(minor_breaks = seq(10, 100, 10)) + geom_rect(xmin = 17, xmax=83, ymin=90, ymax=100, color='black', fill='#6d1d26', size=0.25) + annotate('text', x= 50, y=95, label= "bold('This sentence should be bold.')~'This sentence shouldn\\'t'", size=5, col = 'white', parse = TRUE)
注意plotmath语法里普通文本需要用单引号包裹,空格用~代替,文本内容里的单引号需要转义。
内容的提问来源于stack exchange,提问作者Tanga94
相关产品推荐
相关产品推荐

