gpt4 book ai didi

r - 如何在我的一个方面标签中使用希腊符号?

转载 作者:行者123 更新时间:2023-12-01 09:12:36 25 4
gpt4 key购买 nike

我正在尝试使用 ggplot2 (v. 2_2.2.1) facet_wrap 创建一个绘图,我需要在一个方面标签(五个方面)中只包含一个希腊符号。我尝试使用在 Stack Overflow 上发布的代码:

但没有任何成功(getGrob 不工作,mf_labeller 也是如此)。

有人可以帮我吗?

示例代码如下:

df <- data.frame(genes = rep(c("BA","MLL","pos","neg","PMLalpha+"),5), value = sample(1:100, 25, replace=TRUE))
df$genes <- factor(df$genes, levels = c("BA","MLL","pos","neg","PMLalpha+"), ordered = TRUE)
ggplot(df,aes(x=genes, y=value)) + geom_boxplot()+
facet_wrap(~genes, ncol = 5,scales = "free_x")+
scale_x_discrete(name="",
breaks = c("BA","MLL","pos","neg","PMLalpha+"),
labels = c("BA","MLL","pos","neg",expression(paste("PML", alpha,"+"))))

我可以重命名 x 轴刻度,但我不能在 facet 标签内这样做。

最佳答案

这是一个使用 labeller=label_parsed 的技巧。

首先,为使用要解析的表达式的df$genes 定义标签:

df$genes <- factor(df$genes, levels = c("BA","MLL","pos","neg","PMLalpha+"),
ordered = TRUE, labels=c("BA","MLL","pos","neg",expression(paste("PML", alpha,"+"))))

然后在facet_wrap中使用labeller=label_parsed:

ggplot(df,aes(x=genes, y=value)) + geom_boxplot() + 
facet_wrap(~genes, ncol = 5, scales = "free_x", labeller = label_parsed)

如您所见,这会弄乱 x 轴标签,但您可以在 scale_x_discrete 中修复它,如下所示:

ggplot(df,aes(x=genes, y=value)) + geom_boxplot() + 
facet_wrap(~genes, ncol = 5, scales = "free_x", labeller = label_parsed) +
scale_x_discrete(name="",
breaks = c("BA","MLL","pos","neg","paste(\"PML\", alpha, \"+\")"),
labels = c("BA","MLL","pos","neg", expression(paste("PML", alpha,"+"))))

enter image description here

编辑:作为对发布的后续问题的回应,这里是对多个变量使用 label_parsed 的解决方案。在变量字符串中包含请求的空间。

df$var2 <- c(rep(c('trt a','trt b'), NROW(df)/2),'trt a')
df$var2 <- factor(df$var2, levels=c('trt a','trt b'), ordered=T, labels=c(expression(paste("trt ", alpha)), expression(paste("trt ", beta))))

ggplot(df,aes(x=var2, y=value)) + geom_boxplot() +facet_wrap(~var2, ncol = 5, scales = "free_x", labeller = label_parsed)

固定x轴:

ggplot(df,aes(x=var2, y=value)) + geom_boxplot() + 
facet_wrap(~var2, ncol = 5, scales = "free_x", labeller = label_parsed) +
scale_x_discrete(name="",
breaks = c(expression(paste("trt ", alpha)), expression(paste("trt ", beta))),
labels = c(expression(paste("trt ", alpha)), expression(paste("trt ", beta))))

enter image description here

关于r - 如何在我的一个方面标签中使用希腊符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971945/

25 4 0