mlcyo
mlcyo

Reputation: 614

Adding greek symbol and superscript to ggplot axis text (tickmarks)

I am trying to get the stable oxygen isotope symbol into the axis text (tick mark label) in ggplot.

Example data

df <- data.frame(author = c("one", "two", "three"), 
                 d18O = c("D", "D", "U"),
                 Mg = c("I", "D", "D"),
                 `Drip Rate` = c("U", "I", "I")) %>% 
  pivot_longer(-c(author))  

Exmample plot

df %>% 
  ggplot(aes(x = name, fill = value)) +
  geom_bar(position = "fill", colour = "black", size = 0.1) +
  facet_grid(author~., scales = "free")

scales::parse_format will parse the first part of the symbol (δ^18)

df2 <- df
df2[which(df2$name == "d18O"),]$name <- "delta^18"

df2 %>% 
  ggplot(aes(x = name, fill = value)) +
  geom_bar(position = "fill", colour = "black", size = 0.1) +
  facet_grid(author~., scales = "free") +
  scale_x_discrete(labels = scales::parse_format()) 

enter image description here

But when I try to add the O (to make it δ^18O) I get the error Error in parse(text = text[[i]]) : <text>:1:9: unexpected symbol 1: delta^18O ^

Any help appreciated!

Upvotes: 0

Views: 678

Answers (2)

Mohanasundaram
Mohanasundaram

Reputation: 2949

If the O denotes Omicron, you can use

df2[which(df2$name == "d18O"),]$name <- "delta^~18*Omicron"

Upvotes: 0

drJones
drJones

Reputation: 1233

You need to add an asterisk to escape the superscript:

df2[which(df2$name == "d18O"),]$name <- "delta^18*O"

Upvotes: 1

Related Questions