如何对齐glue生成的多行表达式 实现ggplot2注释垂直对齐
要实现多行注释垂直左对齐,根据你的使用场景可以选择以下方案:
方案1:无数学公式需求,直接拼接换行符
如果两行内容都是普通文本、不需要渲染数学表达式,无需调用parse(),直接用\n拼接两行内容即可,默认就是左对齐:
library(ggplot2) library(glue) b.text <- "bottom part of the expression" t.text <- "top part of the expression" ggplot() + labs(subtitle = glue("{t.text}\n{b.text}"))
方案2:需要渲染数学表达式,调整parse参数
如果你确实需要通过parse()渲染数学公式,只需在原有表达式中添加align = 'left'参数,同时用textstyle保证两行字号一致:
library(ggplot2) library(glue) b.text <- "bottom part of the expression" t.text <- "top part of the expression" ggplot() + labs(subtitle = parse(text = glue("list(atop(textstyle('{t.text}'), textstyle('{b.text}')), align = 'left')")))
方案3:更灵活的富文本注释(推荐)
如果需要更复杂的格式控制,建议使用ggtext包的markdown渲染能力,后续调整格式、插入公式都更方便:
library(ggplot2) library(glue) library(ggtext) b.text <- "bottom part of the expression" t.text <- "top part of the expression" ggplot() + labs(subtitle = glue("{t.text}<br>{b.text}")) + # 配置subtitle用markdown渲染、左对齐 theme(plot.subtitle = element_markdown(hjust = 0))
内容的提问来源于stack exchange,提问作者Indrajeet Patil
相关产品推荐
相关产品推荐

