在 ggplot2 中使用 labeller 更改 facet_wrap 标签

5
在我的ggplot中,我尝试使用labeller(sch.id=paste0("sch.id:", unique(ten$sch.id)))来更改facet_wrap的10个分面标签。然而,图表显示出NA而不是正确的分面标签。我想知道如何修复这个问题?
library(ggplot2)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

ten <- subset(hsb, sch.id %in% unique(sch.id)[1:10])

p <- ten %>% ggplot() + aes(ses, math) + geom_point() +
 facet_wrap(~sch.id) + geom_smooth(method = "lm", se = FALSE)

p + facet_wrap(~sch.id, labeller = labeller(sch.id=paste0("sch.id:", unique(ten$sch.id)))) ## HERE ##
2个回答

4
问题似乎是您将变量传递给了标签函数,但 facet_wrap 已经传递了自己的分面变量。这会导致冲突并产生 NA 的结果。
解决方法是创建一个以变量 x(或任何其他名称,只要不是分面变量的名称)为函数的标签函数,然后使用 as_labeller 进行强制转换为标签器。
请注意,在 facet_wrap 公式中不需要使用 unique,就像不需要使用它一样。
p <- ten %>% ggplot() + aes(ses, math) + geom_point() +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE)

cust_labeller <- function(x) paste0("sch.id:", x)
p + facet_wrap(~ sch.id, 
               labeller = as_labeller(cust_labeller)) ## HERE ##

enter image description here


1
我认为最简单的方法是在绘图之前更改sch.id
library(ggplot2)
ten$sch.id <- paste0("sch.id:", ten$sch.id)

ggplot(ten) + aes(ses, math) + 
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) + 
  facet_wrap(~sch.id)

enter image description here


如果您不想修改数据,而想使用 labeller 参数,您可以创建一个命名向量并在 labeller 中使用它。
cust_label <- setNames(paste0("sch.id:", unique(ten$sch.id)), unique(ten$sch.id))

ggplot(ten) + aes(ses, math) + 
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) + 
  facet_wrap(~sch.id, labeller = as_labeller(cust_label))

1
可以,但是文档支持使用“labeller”。 - rnorouzian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接