刚刚从 roland 和 baptiste 发现了这个非常有用的函数,但需要一个稍微不同的用例,其中原始的 wrap headers 应该由函数转换而不是作为固定值提供。我发布了原始功能的略微修改版本,以防它对其他人有用。它既允许使用命名(固定值)表达式来换行,也允许使用自定义函数和 ggplot2 已经为facet_grid
labeller
参数提供的函数(例如label_parsed
和label_bquote
)。
facet_wrap_labeller <- function(gg.plot, labels = NULL, labeller = label_value) {
#works with R 3.1.2 and ggplot2 1.0.1
require(gridExtra)
# old labels
g <- ggplotGrob(gg.plot)
gg <- g$grobs
strips <- grep("strip_t", names(gg))
modgrobs <- lapply(strips, function(i) {
getGrob(gg[[i]], "strip.text", grep=TRUE, global=TRUE)
})
old_labels <- sapply(modgrobs, function(i) i$label)
# find new labels
if (is.null(labels)) # no labels given, use labeller function
new_labels <- labeller(names(gg.plot$facet$facets), old_labels)
else if (is.null(names(labels))) # unnamed list of labels, take them in order
new_labels <- as.list(labels)
else { # named list of labels, go by name where provided, otherwise keep old
new_labels <- sapply(as.list(old_labels), function(i) {
if (!is.null(labels[[i]])) labels[[i]] else i
})
}
# replace labels
for(i in 1:length(strips)) {
gg[[strips[i]]]$children[[modgrobs[[i]]$name]] <-
editGrob(modgrobs[[i]], label=new_labels[[i]])
}
g$grobs <- gg
class(g) = c("arrange", "ggplot",class(g))
return(g)
}
更新/警告
对于较新版本的gridExtra
包,您将Error: No layers in plot
在运行此函数时收到错误,因为arrange
不再存在gridExtra
并且 R 尝试将其解释为ggplot
. 您可以通过(重新)引入该类的print
函数来解决此问题arrange
:
print.arrange <- function(x){
grid::grid.draw(x)
}
这现在应该允许绘图渲染,您可以ggsave()
像这样使用例如:ggsave("test.pdf", plot = facet_wrap_labeller(p, labeller = label_parsed))
例子
几个用例示例:
# artificial data frame
data <- data.frame(x=runif(16), y=runif(16), panel = rep(c("alpha", "beta", "gamma","delta"), 4))
p <- ggplot(data, aes(x,y)) + geom_point() + facet_wrap(~panel)
# no changes, wrap panel headers stay the same
facet_wrap_labeller(p)
# replace each panel title statically
facet_wrap_labeller(p, labels = expression(alpha^1, beta^1, gamma^1, delta^1))
# only alpha and delta are replaced
facet_wrap_labeller(p, labels = expression(alpha = alpha^2, delta = delta^2))
# parse original labels
facet_wrap_labeller(p, labeller = label_parsed)
# use original labels but modifying them via bquote
facet_wrap_labeller(p, labeller = label_bquote(.(x)^3))
# custom function (e.g. for latex to expression conversion)
library(latex2exp)
facet_wrap_labeller(p, labeller = function(var, val) {
lapply(paste0("$\\sum\\", val, "$"), latex2exp)
})