3

I need to achieve superscript in an axis label within ggplot2, similiar to this question: Superscript and subscript axis labels in ggplot2

However, I will need to write something like this: Ca^2+. This seems not to work with this approach, even if I put the exponent in { } with the bquote command. I tried to read through help("plotmath") but couldn't find an example for my case. I tried escaping the + with \+ and ++ but was not successful.

Edit: I would like to not use any additional packages.

stephanmg
  • 746
  • 6
  • 17

3 Answers3

3

Using the example you provided, this works

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

enter image description here

matushiq
  • 66
  • 4
2

using the ggtext package makes this straight forward. Code shamelessly adapted from Claus Wilke's example in the readme. 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)
  )

Created on 2020-07-21 by the reprex package (v0.3.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94
2

Try to put the superscript as a literal, between quotes.

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

ded an image.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66