【问题标题】:Change geom_text's default "a" legend to label string itself将 geom_text 的默认“a”图例更改为标签字符串本身
【发布时间】:2018-10-02 14:16:14
【问题描述】:

类似于this question,我想更改图例中的默认“a”,但不是完全删除它,而是想用标签本身替换它。也就是说,图例的第一行应该有一个标记为“se”的彩色图标,右侧是全名“setosa”。

iris$abbrev = substr( iris$Species, 1, 2 )
     
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, 
                        shape = Species, colour = Species)) +
    geom_text(aes(label = abbrev))

【问题讨论】:

    标签: r ggplot2 legend geom-text


    【解决方案1】:

    您可以按如下方式处理 grobs:

    p <- ggplot(data = iris, aes(x = Sepal.Length, y=Sepal.Width, shape =
    Species, colour = Species)) +  geom_text(aes(label = abbrev))
    
    g <- ggplotGrob(p)
    lbls <- unique(iris$abbrev)
    g$grobs[[15]][[1]][[1]]$grobs[[4]]$label <- lbls[1]
    g$grobs[[15]][[1]][[1]]$grobs[[6]]$label <- lbls[2]
    g$grobs[[15]][[1]][[1]]$grobs[[8]]$label <- lbls[3]
    
    library(grid)
    grid.draw(g)
    

    【讨论】:

    • 这里的[[15]][[1]][[1]] 是什么?
    • @JackBrookes g$grobs[[15]]guide-box TableGrob(即图例),g$grobs[[15]][[1]] 是一个以guides TableGrob 作为第一个元素的列表。图例的文字元素收集在g$grobs[[15]][[1]][[1]]里面
    • 天哪。好吧,它绝对有效!作为其他人将其推广到其他 ggplots 的注释,您需要通过查看 g$grobs 来替换“15”索引以找到以 TableGrob (5 x 5) "guide-box" 开头的索引。
    • @half-pass ;您可以通过查看名称来找到 grobs,即 g$grobs[[grep("guide", g$layout$name)]]
    【解决方案2】:

    您可以更改图例密钥生成功能。这仍然需要一些人工干预,但可以说比使用 grobs 少。

    library(ggplot2)
    library(grid)
    
    data(iris)
    iris$abbrev = substr( iris$Species, 1, 2 )
    
    oldK <- GeomText$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))`
    GeomText$draw_key <- function (data, params, size, 
                                   var=unique(iris$abbrev), 
                                   cols=scales::hue_pal()(length(var))) {
    
        # sort as ggplot sorts these alphanumerically / or levels of factor
        txt <- if(is.factor(var)) levels(var) else sort(var)
        txt <- txt[match(data$colour, cols)]
    
        textGrob(txt, 0.5, 0.5,  
                 just="center", 
                 gp = gpar(col = alpha(data$colour, data$alpha), 
                           fontfamily = data$family, 
                           fontface = data$fontface, 
                           fontsize = data$size * .pt))
    }
    
    ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width, 
                          shape=Species, colour=Species)) +  
      geom_text(aes(label = abbrev))
    
    
    # reset key
    GeomText$draw_key <- oldK
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2012-01-15
      相关资源
      最近更新 更多