【问题标题】:Color legend key labels with R ggplot2 and remove the keys使用 R ggplot2 为图例键标签着色并删除键
【发布时间】:2020-08-13 10:51:59
【问题描述】:

如何用 R ggplot2 为图例键标签着色并隐藏键本身?

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
geom_point()

图例仅包含文本标签 468,分别以红色、绿色和蓝色着色。

【问题讨论】:

  • scale_color_manual(values = c('4'='red','6'='green','8'='blue')) 添加到您的代码中!
  • @Duck 我认为 OP 希望文本标签以某种颜色显示,例如实际标签 4 以红色打印。
  • @Allan Cameron 是的,完全正确(这就是为什么我添加了“并删除键”以避免混淆)
  • this 建议另一种类似的方式......它实际上用您想要的值更新了图例键。然后你可以取消标签。

标签: r ggplot2


【解决方案1】:

无法直接使用theme 执行此操作,因为element_text 不会采用矢量化输入。可能最容易通过关闭剪切并在图例应该存在的位置绘制一些文本来伪造它:

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
geom_point() +
  geom_text(data = data.frame(wt = c(6, 6, 6, 6), mpg = c(20, 22.5, 25, 27.5),
                              cyl = c(levels(factor(mtcars$cyl)), "cyl"),
                              colour = c(levels(factor(mtcars$cyl)), "cyl")),
            aes(label = colour)) +
  coord_cartesian(xlim = c(1.5, 5.5), clip = "off") +
  scale_color_manual(values = c("blue", "green", "red", "black")) +
  theme(legend.position = "none",
        plot.margin = margin(10, 50, 10, 10))

【讨论】:

    【解决方案2】:

    Allan 的回答也很出色,但这里有一种更自动化的方法,即制作您自己的自定义指南函数。

    library(ggplot2)
    
    guide_textcolourguide <- function(...) {
      guide <- guide_legend(...)
      class(guide) <- c("guide", "textcolourguide", "legend")
      guide
    }
    
    guide_gengrob.textcolourguide <- function(guide, theme) {
      legend <- NextMethod()
    
      # Figure out what are keys and labels
      keys <- grep("^key(?!.*bg)", legend$layout$name, perl = TRUE)
      labels <- grep("^label", legend$layout$name)
      
      # Recolour the labels based on keys, assumes parallel ordering
      newlabels <- mapply(function(key, lab) {
        colour <- legend$grobs[[key]]$gp$col
        lab <- legend$grobs[[lab]]
        lab$children[[1]]$children[[1]]$gp$col <- colour
        return(lab)
      }, key = keys, lab = labels, SIMPLIFY = FALSE)
      
      # Replace labels
      legend$grobs[labels] <- newlabels
      
      # Purge keys
      gtable::gtable_filter(legend, "key", invert = TRUE)
    }
    
    
    ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
      geom_point() +
      scale_colour_discrete(guide = "textcolourguide")
    

    reprex package (v0.3.0) 于 2020-08-13 创建

    【讨论】:

    • 效果也很好!
    • 这在 R 4.0.3 中效果很好。但在 R 4.1.1 中,我收到以下错误消息:获取错误:找不到模式“函数”的对象“guide_textcolourguide”。有希望修复吗?我非常喜欢这个解决方案。
    • 我不确定是什么导致了这个错误,但我认为应该可以做到guide = guide_textcolourguide()。如果这不起作用,我也将其包装成类似的here
    • 太棒了,在 scale_color_manual 中带有 'guide = "stringlegend' 的 ggh4x 包解决了它!还有一个问题,是否有可能保留键并同时使键和标签都着色?
    • 绝对不是ggh4x::guide_stringlegend(),但我想有人可以为此拼凑出一个解决方案。
    【解决方案3】:

    您也可以使用ggtext,方法是重命名cyl 变量并使用element_markdown 作为图例。可能有更优雅的方法来确保因子水平匹配......但这是一种以编程方式为图例提供颜色的方法。

    library(ggplot2)
    library(dplyr)
    library(ggtext)
    
    setColors <- function(x, col="red") 
        paste0("<span style = 'color:", col, ";'>", x, "</span>")
    
    mycols <- setNames(colorspace::rainbow_hcl(length(unique(mtcars$cyl))), 
                       unique(sort(mtcars$cyl)))
    
    mtcars %>% 
        mutate(cyl = factor(setColors(cyl, col= mycols[as.character(cyl)]), 
                            unique(setColors(cyl, col = mycols[as.character(cyl)]))[
                                order(unique(cyl))])) %>% 
        ggplot(aes(wt, mpg, colour = cyl)) + 
        geom_point() +
        theme(legend.text = element_markdown()) +
        scale_color_manual(values = unname(mycols))
    

    reprex package (v0.3.0) 于 2020-08-13 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2019-03-29
      • 2023-03-18
      • 1970-01-01
      • 2023-04-05
      • 2016-04-11
      相关资源
      最近更新 更多