6

Suppose I have the data and plot as follows:

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1))
ggplot(mydata) + geom_point(aes(x=x, y=y)) + facet_wrap(~ tau)

I would like the facet labels to read "tau=0" and "tau=1", respectively, with tau formatted as its greek symbol. I know from another question that using the labeller label_parsed will format the letter tau by itself, but the equal sign seems to complicate things. An ideal solution would not require me to change the data (i.e. make tau a factor and name its levels), but I will take whatever works :)

4

2 回答 2

12

这里有一个解决方案,facet_grid它按级别对 tau 进行索引。

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1))
ggplot(mydata) + geom_point(aes(x=x, y=y)) +
         facet_grid(~ tau,labeller = label_bquote(tau ^ .(x)))

在此处输入图像描述

编辑获得“tau=0”和“tau=1”

facet_grid(~ tau,labeller = label_bquote(tau == .(x)))

Edit2第二个变量 sigma

我通过定义自定义贴标机找到了这个解决方案。希望有人( ggplot2 伙计们)给我一个更简单的解决方案。

在此处输入图像描述

my.label_bquote <- function (expr1 = (tau == .(x)),expr2 = (sigma == .(x))) 
{
   quoted1<- substitute(expr1)
   quoted2 <- substitute(expr2)
   function(variable, value) {
      value <- as.character(value)
      if(variable == 'tau')
         lapply(value, function(x)
               eval(substitute(bquote(expr1, list(x = x)),list(expr1 = quoted1))))
      else
         lapply(value, function(x) 
               eval(substitute(bquote(expr2, list(x = x)),list(expr2 = quoted2))))
   }
}

mydata = data.frame(x=rnorm(4), y=runif(4), tau=c(0,0,1,1),sigma=c(2,2,3,3))
ggplot(mydata) + geom_point(aes(x=x, y=y)) +
  facet_grid(sigma ~ tau,labeller = my.label_bquote())
于 2013-01-06T13:01:09.247 回答
2

有一个更简单的解决方案。为了清楚地了解它们在 labeller 参数中的工作方式,已更改模拟数据变量名称。

mydata = data.frame(x=rnorm(4), y=runif(4), tauvar=c(0,0,1,1),sigmavar=c(2,2,3,3))

ggplot(mydata) + 
   geom_point(aes(x=x, y=y)) +
   facet_grid(sigmavar ~ tauvar,labeller = label_bquote(sigma==.(sigmavar),
                                                   tau==.(tauvar)))
于 2018-06-15T02:28:20.073 回答