【问题标题】:Superscript in axis labels in ggplot2 for ionsggplot2中离子轴标签中的上标
【发布时间】:2020-07-21 08:22:49
【问题描述】:

我需要在ggplot2中的轴标签中实现上标,类似于这个问题:Superscript and subscript axis labels in ggplot2

但是,我需要这样写:Ca^2+。这似乎不适用于这种方法,即使我使用bquote 命令将指数放入{ }。我试图通读help("plotmath"),但找不到适合我的例子。我尝试使用\+++ 转义+,但没有成功。

编辑:我不想使用任何额外的包。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    尝试将上标作为文字放在引号之间。

    g <- ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot()
    g + xlab(bquote('Superscript as a literal' ~~ Ca^'2+'))
    

    【讨论】:

    • @stephanmg 我想是的,是的。这取决于文本和符号之间所需的空间量。
    • 我想我可以接受这个答案,很抱歉我不能接受多个答案。
    【解决方案2】:

    使用ggtext 包可以直接实现这一点。 代码无耻地改编自自述文件中 Claus Wilke 的示例。 https://github.com/wilkelab/ggtext

    library(tidyverse)
    library(ggtext)
    library(glue)
    
    data <- tibble(
      atom = "Ca",
      charge = "2+",
      value = -0.5
    )
    
    data %>% mutate(
      color = "#009E73",
      name = glue("<i style='color:{color}'>{atom}</i><b><sup>{charge}</sup></b>"),
      name = fct_reorder(name, value)
    )  %>%
      ggplot(aes(value, name, fill = color)) + 
      geom_col(alpha = 0.5) + 
      scale_fill_identity() +
      labs(caption = "Example shamelessly adapted from Claus Wilke") +
    theme(
        axis.text.y = element_markdown(),
        plot.caption = element_markdown(lineheight = 1.2)
      )
    

    reprex package (v0.3.0) 于 2020 年 7 月 21 日创建

    【讨论】:

    • 我什至可能把它复杂化了——我添加了 标签,因为我认为 OP 也想让上标加粗。
    • 谢谢@Tjebo。粗体实际上是不必要的。
    【解决方案3】:

    使用您提供的示例,这是可行的

    library(ggplot2)
    qplot(uptake, data = CO2) +
      xlab(bquote('Assimilation ('*mu~ 'mol' ~Ca^{"2+"} ~ m^-2~s^-1*')'))
    

    【讨论】:

    • 开枪!我没想过使用引号,谢谢@matushiq。
    猜你喜欢
    • 2016-04-25
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2018-01-31
    相关资源
    最近更新 更多