【问题标题】:Show letters as key glyphs for geom_text legend instead of default 'a'将字母显示为 geom_text 图例的关键字形,而不是默认的“a”
【发布时间】:2018-07-24 13:20:42
【问题描述】:

我正在使用 geom_raster 和 geom_text 在我的绘图中的每个彩色矩形上放置一个字母。我希望这封信也出现在图例中的颜色框顶部,但不知道如何。

我尝试将show.legend=TRUE 添加到geom_text,但这会导致每个图例键中出现字母“a”,而不是所需的字符。

想要的结果如下:

这是重现基本情节的代码:

library(tidyverse)
d <-tribble(
    ~a, ~b, ~c,
    "a", "l", "A",
    "a", "r", "F",
    "b", "l", "Q",
    "b", "r", "R"
)

ggplot(data=d, aes(x=a, y=b, fill=c)) +
    geom_raster(na.rm=TRUE) +
    geom_text(aes(label=c), size=3, na.rm=TRUE) 

还有输出:

这可能与此问题有关:https://github.com/tidyverse/ggplot2/issues/2004,但也许有解决方法?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以改用geom_point将点形状指定为字母scale_shape_manual(values = d$c)

    # We have to remove legend text and label with theme
    ggplot(d, aes(a, b, fill = c, shape = c)) +
        geom_raster() +
        geom_point(size = 3) +
        scale_shape_manual(values = d$c) +
        theme(legend.text = element_text(size = 0),
              legend.title = element_text(size = 0))
    

    【讨论】:

      【解决方案2】:

      你可以在将 ggplot 对象变成一个 grob 后破解它:

      # store the original ggplot object as p
      p <- ggplot(data=d, aes(x=a, y=b, fill=c)) +
        geom_raster(na.rm=TRUE) +
        geom_text(aes(label=c), size=3, na.rm=TRUE, show.legend = TRUE) 
      
      # convert to grob
      gp <- ggplotGrob(p)
      
      grid::grid.draw(gp) # can verify the plot here. Should look the same as before.
      

      现在我们可以检查 grob 对象的层次结构以找到合适的槽来更改图例键。也可以以编程方式执行此操作,但除非您的用例涉及生成许多具有不同数量的图例键的不同图表,否则我发现读取控制台输出更容易:

      gp # this shows the 15th grob in gp corresponds to "guide-box" (i.e. legend)
      
      gp$grobs[15][[1]] # this shows the the first grob of the above corresponds to "guides"
      
      gp$grobs[15][[1]]$grobs[1][[1]] 
      # this shows the 5th / 8th / 11th / 14th grobs of the above correspond to the text on legend keys
      
      str(gp$grobs[15][[1]]$grobs[1][[1]]$grobs[5][[1]])
      # each of the legend key texts is a list, with a slot for "label"
      

      相应地更改图例键:

      gp$grobs[15][[1]]$grobs[1][[1]]$grobs[5][[1]]$label <- "A"
      gp$grobs[15][[1]]$grobs[1][[1]]$grobs[8][[1]]$label <- "F"
      gp$grobs[15][[1]]$grobs[1][[1]]$grobs[11][[1]]$label <- "Q"
      gp$grobs[15][[1]]$grobs[1][[1]]$grobs[14][[1]]$label <- "R"
      
      # check the amended plot
      grid::grid.draw(gp)
      

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多