这里有一个"dirty hack",因为
ggplot
没有提供更改标签背景的API。
免责声明:此方法假定底层的
grobs
具有某种结构,可能无法保证。因此,请小心使用。
library(ggplot2)
library(grid)
library(gtable)
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_boxplot()
g <- ggplotGrob(p)
guide <- g$grobs[[which(g$layout$name == "guide-box")]]
guides <- guide$grobs[[which(guide$layout$name == "guides")]]
cols <- vapply(guides$grobs[grep("^key.+[^b][^g]$", guides$layout$name)],
function(gt) gt$gp$fill, character(1))
pos <- guides$layout[grep("^label", guides$layout$name),
c("t", "l", "b", "r", "z")]
for (i in seq_along(cols)) {
guides <- gtable_add_grob(guides,
rectGrob(gp = gpar(fill = cols[i])),
pos[i, "t"],
pos[i, "l"],
pos[i, "b"],
pos[i, "r"],
pos[i, "z"] - 1,
name = paste0("key-bg-", i))
}
guide$grobs[[which(guide$layout$name == "guides")]] <- guides
g$grobs[[which(g$layout$name == "guide-box")]] <- guide
grid.draw(g)
![Colored Keys](https://istack.dev59.com/jBXXq.webp)