如何在 ggplot2 的多面图的单个标签中使用特殊字符、上标或下标?

how can I use special characters, superscripts or subscripts in a single label of faceted plots in ggplot2?

我想将上标和/或下标添加到像这样的多面绘图布局中的条带文本标签的子集:

conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>% mutate(mass_area = conc/Petal.Length*Sepal.Length)

melted <- reshape2::melt(df)
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) + 
  geom_boxplot() +
  theme_ipsum() +
  scale_fill_brewer(palette = "Greens") +
  theme(
    legend.position = "bottom",
    plot.title = element_text(size = 10)) +
  theme(axis.text.x = element_blank(),
        strip.text = element_text(size = 12)) +
  ggtitle(mytitle) +
  xlab("") +
  ylab("") +
  facet_wrap(~variable, scale = "free")
bp1

但是 mass_area 应该有一个格式为 lab = expression("Chl concentration" ~ (mu ~ g ~ " " ~ cm^{-2}))

的标签

响应很有用,但根据相同的模式标记所有方面。我只需要标记一个。

在您链接的 post 之后,一个选项是使用 ifelse 有条件地设置标签,如下所示:

library(dplyr)
library(ggplot2)
library(hrbrthemes)

set.seed(42)

conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>% 
  mutate(mass_area = conc/Petal.Length*Sepal.Length)

melted <- reshape2::melt(df) %>% 
  mutate(variable = ifelse(variable == "mass_area",
                           paste0("Chl~concentration ~ (mu ~ g ~ cm^{-2})"), 
                           paste0(variable)))

#> Using Species as id variables

bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) + 
  geom_boxplot() +
  theme_ipsum() +
  scale_fill_brewer(palette = "Greens") +
  theme(
    legend.position = "bottom",
    plot.title = element_text(size = 10)) +
  theme(axis.text.x = element_blank(),
        strip.text = element_text(size = 12)) +
  ggtitle("mytitle") +
  xlab("") +
  ylab("") +
  facet_wrap(~variable, scale = "free", labeller = label_parsed)
bp1

这是一种使用 tidyverse 包的方法。我使用 pivot_longer() 而不是 melt() 并且 case_when() 而不是 ifelse() 只是为了给你第二个解决方案,但最后它做同样的事情,因为它是矢量化的 ifelse。 这为您提供与 stefans 解决方案相同的结果。

附带说明:我已经更正了表达方式,因此微克中不再有 space。

library(dplyr)
library(tidyr)
library(ggplot2)
 
 conc <- runif(nrow(iris), min = 5, max = 10)
 df <- iris %>% mutate(mass_area = conc/Petal.Length*Sepal.Length)
 
 melted <- df %>% pivot_longer(cols = -Species,
                               names_to = "variable") %>% 
    mutate(variable = case_when(variable == "mass_area" ~ paste0("Chl~concentration ~ (mu*g ~ cm^{-2})"),
                                TRUE ~ as.character(variable))
    )
 
 bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) + 
    geom_boxplot() +
    scale_fill_brewer(palette = "Greens") +
    theme(
       legend.position = "bottom",
       plot.title = element_text(size = 10)) +
    theme(axis.text.x = element_blank(),
          strip.text = element_text(size = 12)) +
    xlab("") +
    ylab("") +
    facet_wrap(~variable, scale = "free", label = "label_parsed")
 bp1