在R的ggpub::ggboxplot中使用原始字符串,而不是转义字符串

wz3gfoph  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(290)

如何使用R中ggpubr::ggboxplot的列名中的原始字符串(如len/s)?这似乎是由于purrr::map

library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth

colnames(df) <- c("len/s", "supp", "dose%sd")

ggboxplot(df, x = "dose%sd", y = 'len/s',
               color = "dose%sd", palette =c("#00AFBB", "#E7B800", "#FC4E07"),
               add = "jitter", shape = "dose%sd")

有误差

Error in `purrr::pmap()`:
ℹ In index: 1.
ℹ With name: len/s.
Caused by error in `purrr::map()`:
ℹ In index: 1.
ℹ With name: x.
Caused by error in `parse()`:
! <text>:1:5: unexpected input
1: dose%sd

---
Backtrace:
  1. ggpubr::ggboxplot(...)
 15. purrr::map(., function(x) parse_expression(x))
 16. purrr:::map_("list", .x, .f, ..., .progress = .progress)
 20. ggpubr (local) .f(.x[[i]], ...)
 21. ggpubr:::parse_expression(x)
 22. base::parse(text = x)
yhqotfr8

yhqotfr81#

默认情况下,parse_aes选项设置为TRUE

> ggpubr_options()
$ggpubr.parse_aes
[1] TRUE

我们可以将parse_aes选项设置为FALSE,并在绘制后重置

library(ggpubr)
op <- options(ggpubr.parse_aes = FALSE)
colnames(df) <- c("len/s", "supp", "dose%sd")

ggboxplot(df, x = "dose%sd", y = 'len/s',
          color = "dose%sd", palette =c("#00AFBB", "#E7B800", "#FC4E07"),
          add = "jitter", shape = "dose%sd")

options(op)
  • 输出

ggboxplot调用ggboxplot_core内部函数,该函数使用create_aes调用ggplot,其中parse = TRUE

> ggpubr:::ggboxplot_core
...
p <- ggplot(data, create_aes(list(x = x, y = y)))
...
> create_aes
function (.list, parse = TRUE) 
{
    if (missing(parse)) {
        parse <- base::getOption("ggpubr.parse_aes", default = TRUE)
    }
    if (parse) {
        return(create_aes.parse(.list))
    }
    else {
        return(create_aes.name(.list))
    }
}

create_aes.parse调用parse_expression,而create_aes.name转换为符号

> ggpubr:::create_aes.parse
function (.list) 
{
    .list <- .list %>% purrr::map(function(x) parse_expression(x))
    do.call(ggplot2::aes, .list)
}

> ggpubr:::create_aes.name
function (.list) 
{
    .list <- .list %>% purrr::map(function(x) to_name(x))
    do.call(ggplot2::aes, .list)
}

因此,更容易将parse_aes设置为FALSE

相关问题