【问题标题】:Recoloring Legend Text Background in ggplot2在ggplot2中重新着色图例文本背景
【发布时间】:2021-10-31 23:46:06
【问题描述】:

使用此代码:

ggplot(mtcars, aes(x=mtcars$mpg, y = mtcars$wt, color = as.factor(mtcars$cyl))) + geom_point()

我得到了一个不错的情节,如下所示:

出于我的目的,我希望图例看起来像这样:

换句话说,我希望颜色图例的图例文本的背景与标签的相应颜色相匹配。有什么简单的方法吗?

编辑:在我当前的代码中,我将ggtextscale_color_hue(labels = colorLabels) 一起使用,其中colorLabels 看起来像这样<span style='color:red'>MyLabel</span> 使文本本身着色,但我不太喜欢它,我想要看看我对交换颜色的感觉。将color:redbackground-color:red 切换只会删除文本颜色,实际上不会为背景着色。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    这是一个肮脏的 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()
    
    ## 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)
    

    【讨论】:

    • 我已经接受了这个作为答案,但我希望有一种方法可以让我的同事在我离开时能理解它哈哈。谢谢!
    猜你喜欢
    • 2017-12-13
    • 2022-01-09
    • 2015-12-25
    • 2021-04-08
    • 2022-01-08
    • 2023-03-24
    • 2023-04-03
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多