【问题标题】:left aligned two-lined text with special characters in ggplot2ggplot2中带有特殊字符的左对齐两行文本
【发布时间】:2021-09-05 06:54:56
【问题描述】:

我尝试了两种方法来尝试在我的图中插入文本,以指定 R² 和 ggplot2 图中的回归斜率。

首先重要的是 R² 以 2 为上标,我已将其值和斜率值保存在我必须调用的变量中,斜率的单位是我想要的 nmol/g*h显示为 nmol⋅g⁻¹⋅h⁻¹,并且 R² 和斜率应显示在左对齐的两条线上,位于绘图的左上角。

我尝试了以下方法:

  • 使用表达式、粘贴和 unicode:
text <- 
   expression(paste(
      paste(R^2, "=", r_squared, sep = " "), 
      paste("Slope =", slope, "nmol\u22c5g\u207B\u00B9\u22c5h\u207B\u00B9", sep = " "),
      sep = "\n"
   ))
  • 使用 bquote 和 atop:
text <- 
   bquote(atop(
     R^2 == .(r_squared_singledata),
     "Reaction rate" == .(slope_singledata)~nmol%.%g^-1%.%h^-1))

在这两种方式中,我都将这些表达式保存在一个变量中并稍后调用:

info_box <- grobTree(textGrob(text, x = 0.01, y = 0.99, 
                                hjust = 0, vjust = 1, gp = gpar(fontsize = 8)))
ggplot(data = mydata, aes(x,y))+
annotation_custom(info_box)

问题是,在第一种方式中,由于 unicode,我得到了转换错误。而在第二种方式中,文本居中而不是左对齐。

我发现了一个类似的问题here,但我无法调整它来解决我的问题...

有没有人知道在绘图内的两行文本中使用指数和变量的方法,可以左对齐并放置在我喜欢的任何位置?

【问题讨论】:

  • sprintf 使用 unicode 的解决方案是否适合您? stackoverflow.com/q/26752779/6288065
  • @LC-datascientist 遗憾的是它没有......但我发现我的回答中描述了一种相当简单的方法

标签: r ggplot2


【解决方案1】:

好的,以供参考,以防有人想做类似的事情:

在定义文本时,实际上不需要使用复杂花哨的表达方式。只需使用 gridtext 包中的richtext_grob() 命令,即可在字符串中使用 HTML 和 Markdown 命令。

我的解决方案现在如下所示:

library(gridtext)

# The <br> causes a line-break, <sup> and </sup> enter and escape superscript
text <- paste(
      paste("R<sup>2</sup> = ", r_squared),
      "<br>",
      paste("Slope = ", slope, " nmol g<sup>-1</sup> h<sup>-1</sup>")
    )

# Use of richtext_grob() instead of textGrob()
info_box <- grobTree(
        richtext_grob(text, x = 0.01, y = 0.99, 
                      hjust = 0, vjust = 1, gp = gpar(fontsize = 8))
        )

ggplot(data = mydata, aes(x,y))+
annotation_custom(info_box)

可以在here 或官方CRAN 网站上找到其他可能的文本格式。

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 2015-05-15
    • 2020-11-12
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2022-10-23
    • 2018-02-05
    • 1970-01-01
    相关资源
    最近更新 更多