ggplot中解析含上下标的标题时,主题加粗样式未生效问题问询
解决ggplot解析后标题无法加粗的问题
当你用parse()处理带下标/上标的标题时,theme()里的face="bold"不会对解析后的表达式生效,因为表达式的样式由自身语法控制。这里提供两种可行的解决方法:
方法1:在解析表达式中直接指定加粗
在parse()的文本参数里用bold()函数包裹整个表达式,解析后的标题会自动加粗,同时可保留原theme设置:
library(ggplot2) library(gridExtra) df <- data.frame(Letter_x=c(LETTERS[1:3]), Value_y=c(1:3)) # 在表达式中加入bold()实现加粗 my_title1 = parse(text="bold(NO[3])") my_title2 = "NO3" plot_theme = theme( plot.title = element_text(size = 14, face = "bold", margin=margin(0, 0, 3, 0), hjust=.5) ) p1 <- ggplot(df, aes(Letter_x, Value_y)) + geom_point() + ggtitle(my_title1)+ plot_theme p2 <- ggplot(df, aes(Letter_x, Value_y)) + geom_point() + ggtitle(my_title2)+ plot_theme grid.arrange(p1, p2, ncol=2, nrow = 1)
方法2:使用ggtext包支持Markdown语法
如果需要更灵活的样式控制(比如混合加粗、下标/上标),可以用ggtext包的element_markdown(),直接用Markdown语法写标题,无需parse():
library(ggplot2) library(gridExtra) library(ggtext) df <- data.frame(Letter_x=c(LETTERS[1:3]), Value_y=c(1:3)) # 用Markdown语法:**表示加粗,~表示下标 my_title1 = "**NO~3~**" my_title2 = "**NO3**" plot_theme = theme( # 替换为element_markdown()以支持Markdown语法 plot.title = element_markdown(size = 14, margin=margin(0, 0, 3, 0), hjust=.5) ) p1 <- ggplot(df, aes(Letter_x, Value_y)) + geom_point() + ggtitle(my_title1)+ plot_theme p2 <- ggplot(df, aes(Letter_x, Value_y)) + geom_point() + ggtitle(my_title2)+ plot_theme grid.arrange(p1, p2, ncol=2, nrow = 1)
两种方法都能让两张图的标题同时显示加粗效果,方法2更适合复杂的样式组合。
内容的提问来源于stack exchange,提问作者Martin Liungman
相关产品推荐
相关产品推荐

