【问题标题】:ggplot removes geom_label border from legendggplot 从图例中删除 geom_label 边框
【发布时间】:2020-12-15 01:51:25
【问题描述】:

由于某种原因,ggplot 在您使用geom_label 时为实际点添加了边框,但图例中不包含边框。一个简单的例子:

library(tidyverse)

mtcars %>%
  rownames_to_column('car') %>%
  slice(1:10) %>%
  ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
  geom_label() +
  scale_x_continuous(limits = c(2, 10))

我希望图例中的那些小“a”也有红色和蓝色边框(不是整个图例周围的边框,为了清楚起见),但我不知道怎么做。我探索过在guides 函数中使用override.aes 选项,但不知道是否可以通过这种方式添加边框。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    正如@r2evans 所说,现在很难通过简单的方式做到这一点。
    我的答案是通过创建和替换函数来实现的,GeomLabel$draw_key。
    (注意:此答案基于Change geom_text's default "a" legend to label string itself)

    library(tidyverse); library(grid)
    
    oldK <- GeomLabel$draw_key # to save for later
    
    # define new key
    # if you manually add colours then add vector of colours 
    # instead of `scales::hue_pal()(length(var))`
    GeomLabel$draw_key <- function (data, params, size#, 
                                    # var=unique(iris$abbrev), 
                                    # cols=scales::hue_pal()(length())
                                    ) {
    
      gr <- roundrectGrob(0.5, 0.5, width = 0.9, height = 0.9,
                just = "center",
                gp = gpar(col = data$colour, fill = NA))
      gt <- textGrob("a", 0.5, 0.5,
               just="center",
               gp = gpar(col = alpha(data$colour, data$alpha),
                         fontfamily = data$family,
                         fontface = data$fontface,
                         fontsize = data$size * .pt))
      grobTree(gr, gt)
    }
    
    mtcars %>%
      rownames_to_column('car') %>%
      slice(1:10) %>%
      ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
      geom_label() +
      scale_x_continuous(limits = c(2, 10))
    
    # reset key
    GeomLabel$draw_key <- oldK
    

    【讨论】:

      【解决方案2】:

      我认为在图例组件周围“默认”添加一个框可能是一个功能请求(对于ggplot2/issues)。同时,这是一个我希望其他人可以用更合理的版本替换的 hack。

      添加一个空的geom_rect。

      mtcars %>%
        rownames_to_column('car') %>%
        slice(1:10) %>%
        ggplot(aes(cyl, mpg, label = car, col = factor(am))) +
        geom_label() +
        scale_x_continuous(limits = c(2, 10)) +
        geom_rect(xmin = NA, xmax = NA, ymin = NA, ymax = NA, fill = NA, na.rm = TRUE)
      

      【讨论】:

      • 是的,这是一个 hack,但我会接受。一件事——如果我override 将默认文本从“a”更改为其他内容,则该框不会随着文本长度而增长。即添加...+ guides(color = guide_legend(override.aes = list(label = c('thisthis', 'thatthat'))))
      猜你喜欢
      • 2022-08-11
      • 2016-04-09
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      相关资源
      最近更新 更多