ggplot2 facet_grid自定义标签与组,下标和值 [英] ggplot2 facet_grid custom labeller with group, subscript and value
问题描述
facet_grid
添加(1) group(|,A ['i,j '],|)
和(2) value
? 对于(1),使用 expression()
,我只能在没有 值的情况下使用
:
plot_labeller< - function(variable,value){
print(value )
if(variable =='FOO'){
expr1< - expression(group(|,A ['i,j'],|))
return (expr1)
} else {
return(bla)
}
}
对于(2),显示值
,使用 paste()
适用于只是简单的数学表达式。例如:
plot_labeller< - function(variable,value){
if(variable =='FOO' ){
expr1< - paste(alpha,:,value)
return(expr1)
} else {
return(bar)
}
}
然而, paste()
不适用于 group()
(e:找不到函数group)。即使没有 group()
也不起作用:A ['i,j']然后按原样显示,即不应用 plotmath
。使用 bquote()
如下:
plot_labeller< - function变量,值){
if(变量=='FOO'){
expr1< - bquote(group(|,A ['i,j'],|):。 (value))
return(expr1)
} else {
return(bar)
}
}
不起作用:
labels [,i]< - labeller(names(label_df)[i],label_df [,i]):
要替换的项目数不是替换长度的倍数
$ c $不过,使用text()
打印带引号的表达式是有效的。 $
> b $ b解决方案我确定有一个更简单更好的方法,但是这里有一个想法:
<$ (ggplot2)
d< - data.frame(x = 1:10,y = 1:10,f = gl(2,5,标签= c(FOO,BLAH)))
make_label< - 函数(值)
bquote(group(|,A ['i,j'], |):。(value))
plot_labeller< - 有趣ction(variable,value){
print(value)
if(variable =='f')
do.call(表达式,lapply(levels(value)[value],make_label) )elseother
}
qplot(x,y,data = d)+ facet_grid(。〜f,labeller = plot_labeller)
In summary, my question is how to create labels for facet_grid
with (1) group("|",A['i,j'],"|")
and (2) value
?
For (1), using expression()
, I can only get it to work without value
:
plot_labeller <- function(variable,value){
print(value)
if (variable=='FOO') {
expr1 <- expression(group("|",A['i,j'],"|"))
return(expr1)
} else {
return("bla")
}
}
For (2), displaying the value
, using paste()
works for rather simple math expr, only. For example:
plot_labeller <- function(variable,value){
if (variable=='FOO') {
expr1 <- paste("alpha"," : ",value)
return(expr1)
} else {
return("bar")
}
}
However, paste()
does not work with group()
(e: could not find function "group"). Even without group()
it does not work: "A['i,j']" is then displayed "as is", i.e., without applying plotmath
. Using bquote()
as in:
plot_labeller <- function(variable,value){
if (variable=='FOO') {
expr1 <- bquote(group("|",A['i,j'],"|") : .(value))
return(expr1)
} else {
return("bar")
}
}
does not work, either:
Error in labels[, i] <- labeller(names(label_df)[i], label_df[, i]) :
number of items to replace is not a multiple of replacement length
Printing the bquoted expression with text()
works, though.
I'm sure there's a simpler and better way, but here's an idea:
library(ggplot2)
d <- data.frame(x=1:10, y=1:10, f=gl(2,5, labels=c("FOO","BLAH")))
make_label <- function(value)
bquote(group("|",A['i,j'],"|"):.(value))
plot_labeller <- function(variable,value){
print(value)
if(variable=='f')
do.call(expression, lapply(levels(value)[value], make_label)) else "other"
}
qplot(x,y,data=d) + facet_grid(.~f, labeller=plot_labeller)
这篇关于ggplot2 facet_grid自定义标签与组,下标和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!