rolandとbaptisteからこの非常に便利な関数に出くわしましたが、元のラップヘッダーを固定値として提供するのではなく、関数によって変換する必要がある、わずかに異なるユースケースが必要でした。他の人に役立つ場合に備えて、元の関数のわずかに変更されたバージョンを投稿しています。これにより、ラップストリップに名前付き(固定値)式を使用できるだけでなく、カスタム関数と、facet_grid
labeller
パラメーター(label_parsed
およびなどlabel_bquote
)に対してggplot2によって既に提供されている関数を使用することもできます。
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)
})