将希腊符号和上标添加到 ggplot 轴文本(刻度线)

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

我正在尝试将稳定的氧同位素符号放入 ggplot 的轴文本(刻度标记标签)中。

示例数据

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))  

示例图

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

scales::parse_format 将解析符号的第一部分 (δ^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()) 

但是当我尝试添加 O(使其成为 δ^18O)时,我得到错误 Error in parse(text = text[[i]]) : <text>:1:9: unexpected symbol 1: delta^18O ^

感谢任何帮助!

您需要添加一个星号来转义上标:

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

如果O表示Omicron,可以用

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