在 ggplot2 中重新着色图例文本背景

标签 r ggplot2 legend

使用此代码:

ggplot(mtcars, aes(x=mtcars$mpg, y = mtcars$wt, color = as.factor(mtcars$cyl))) + geom_point()
我得到一个很好的情节,看起来像这样:
enter image description here
出于我的目的,我希望图例看起来像这样:
enter image description here
换句话说,我希望颜色图例的图例文本的背景与标签的相应颜色相匹配。有没有简单的方法可以做到这一点?
编辑:在我当前的代码中,我使用的是 ggtextscale_color_hue(labels = colorLabels)哪里colorLabels看起来像这样 <span style='color:red'>MyLabel</span>让文本本身着色,但我不太喜欢它,我想看看我对颜色交换的感觉。切换 color:redbackground-color:red只是删除文本颜色,实际上并不为背景着色。

最佳答案

这是一个肮脏的黑客,如 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()

## 1. Store ggplot object as grob
g <- ggplotGrob(p)

## 2. Find and retrieve the guidebox and guides
guide <- g$grobs[[which(g$layout$name == "guide-box")]]
guides <- guide$grobs[[which(guide$layout$name == "guides")]]

## 3. Get the fill colors of the guide
## N.B. This works in this toy example because the key has a fill property, 
## this may be different for other geoms
cols <- vapply(guides$grobs[grep("^key.+[^b][^g]$", guides$layout$name)],
               function(gt) gt$gp$fill, character(1))

## 4. Get the positions of the labels
pos <- guides$layout[grep("^label", guides$layout$name), 
                     c("t", "l", "b", "r", "z")]

## 5. Add colored rects below the labels
## N.B. These span the width of labels
## some more work would be needed to make them bigger and/or center the labels
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))
}

## 6. Write back the guides to the original object
guide$grobs[[which(guide$layout$name == "guides")]] <- guides
g$grobs[[which(g$layout$name == "guide-box")]] <- guide

## 7. Draw the graph
grid.draw(g)
Colored Keys

关于在 ggplot2 中重新着色图例文本背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69031286/

相关文章:

r - 在传单图例 R 中显示自然中断间隔

r - 在 map 上独立移动 2 个图例 ggplot2

r - 错误 ggplotly : VECTOR_ELT() can only be applied to a 'list' , 不是 'NULL'

R ggplot2图例里面的图

r - 测试空 bool 集的相等性

r - 更改构面标签文本和背景颜色

R - 如何将多个 bool 列(不知道有多少)组合成一列

r - 如何在 R 中生成 3-D 条形图?

在多个图中重用 ggplot 图层

r - 当我设置 x 和 y 限制时,ggplot 会删除所有数据