我想创建自己的贴标机函数来获取facet标签的输入,将其转换为包含数学符号的字符串,然后让ggplot解析它 . 我知道我可以更改基础数据并使用 label_parsed ,但希望能够使用其他人可以使用的易于推广的功能 . 这也允许人们按原样保存数据(包括正确的因子水平)并只交换标签 . 否则,您需要改变基础数据,然后添加正确的因子级别,以便正确完成排序 .

看完http://ggplot2.tidyverse.org/reference/labeller.html这里's what I'试过了 .

library(ggplot2)

## can be used with label_parsed but order not retained
mtcars$mpg2 <- ifelse(mtcars$mpg > 20, 'beta', 'alpha')
## can be used with label_parsed and retains levels (but this is 2 steps)
mtcars$mpg3 <- factor(mtcars$mpg2, levels = c('beta', 'alpha'))

ggplot(mtcars, aes(mpg, disp)) +
    geom_point() +
    facet_grid(mpg3 ~ mpg2, 
        labeller = label_parsed
    )

## attempt #1 at a function
label_as_notation <- function(x, ...){
    parse(text = paste('"X:" ~ ', x, '<=', ifelse(x == 0, 'omega', 'psi')))
}

ggplot(mtcars, aes(mpg, disp)) +
    geom_point() +
    facet_grid( ~ am, 
        labeller = labeller(am = label_as_notation)
    )

enter image description here

所以我想知道 label_parsed 做了什么?

> label_parsed(1:3)
[[1]]
[[1]][[1]]
expression(1)


[[2]]
[[2]][[1]]
expression(2)


[[3]]
[[3]][[1]]
expression(3)

表达式列表的列表 . 所以我尝试过:

label_as_notation2 <- function(x, ...){

    y <- unlist(x)

    lapply(x, function(y) { 
        lapply(y, function(z) {
            parse(text = paste('"X:" ~ ', z, '<=', ifelse(z == 0, 'omega', 'psi')))
        })
    })
}

ggplot(mtcars, aes(mpg, disp)) +
    geom_point() +
    facet_grid( ~ am, 
        labeller = labeller(am = label_as_notation2)
    )

enter image description here

如果我将 label_parsed 变成函数,就会发生类似的想法:

ggplot(mtcars, aes(mpg, disp)) +
    geom_point() +
    facet_grid( ~ am, 
        labeller = labeller(am = function(x) label_parsed(x))
    )

enter image description here

所以我觉得's not surprising my second approach didn'工作 . 我试过 as_labeller 包裹返回字符但不解析的函数 .

如何制作一个可推广的贴标机,可以动态切换带有数学概念的标签,以便ggplot2正确解析它们?