我想在
expression
面标签中有一个 R ggplot2
。
假设我正在策划
tips
data.frame
:
library(reshape2)
> head(tips)
total_bill tip sex smoker day time size
1 16.99 1.01 Female No Sun Dinner 2
2 10.34 1.66 Male No Sun Dinner 3
3 21.01 3.50 Male No Sun Dinner 3
4 23.68 3.31 Male No Sun Dinner 2
5 24.59 3.61 Female No Sun Dinner 4
6 25.29 4.71 Male No Sun Dinner 4
如下:
library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol = 1)
我不想将“女性”和“男性”作为方面标签,而是: 分别为“Female subjects”和“Male subjects”。据我所知,R 中的斜体标签是通过
expression
函数实现的,但我不知道如何将其与 facet_wrap
结合起来。
截至
ggplot2
2.1.0
:
data(tips, package="reshape2")
library(ggplot2)
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol=1,
labeller=label_bquote(.(levels(tips$sex)[sex])~subjects))
看起来过于复杂,但有效。不过,您必须使用
facet_grid
。
make_label <- function(value) {
x <- as.character(value)
bquote(italic(.(x))~subjects)
}
plot_labeller <- function(variable, value) {
do.call(expression, lapply(levels(value), make_label))
}
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_grid(.~sex, labeller = plot_labeller)
以下适用于 R 4.0.3 和 ggplot2 3.3.2
library(ggplot2)
data(tips, package="reshape2")
tips$sex = as.character(tips$sex)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol = 1, labeller = label_bquote(italic(.(sex))~subjects))
sp
它按照@Stéphane Laurent 的建议使用
label_bquote
,但不需要将级别转换为 bquote 中的正确字符,这对我来说是失败的。
我知道这是一篇旧帖子,但我喜欢
label_parsed
功能。它与factor
中的标签一起使用:
data(tips, package="reshape2")
library(ggplot2)
tips %>%
mutate(sex = factor(sex,
levels = c("Female", "Male"),
labels = c(expression(italic(Female)~Subjects),
expression(italic(Male)~Subjects)))) %>%
ggplot(aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_wrap(~sex, ncol = 1,labeller = label_parsed)