在保留标签的同时删除ggplot图例符号

时间:2017-09-01 17:06:29

标签: r ggplot2 legend

示例代码和图:

data <- data.frame( ID = c(LETTERS[1:26], paste0("A",LETTERS[1:26])),
                    Group = rep(c("Control","Treatment"),26),
                    x = rnorm(52,50,20),
                    y = rnorm(52,50,10))

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
   geom_text(size=8) + 
   scale_color_manual(values=c("blue","red")) +
   theme_classic() +
   theme(legend.text = element_text(color=c("blue","red")))

enter image description here

我要解决的是删除图例符号(“a”)并为组标签(控制和处理)着色,因为它们出现在图中(分别为蓝色和红色)。

我试过了:

geom_text(show_guide = F)

但这完全取消了传说。

为了保持简单,我可以使用注释...但是想知道是否有特定于传奇的解决方案。

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) +
   geom_text(size=8, show_guide=F) +
   scale_color_manual(values=c("blue","red")) +
   theme_classic() +
   annotate("text",label="Control", color="blue",x=20,y=80,size=8) +
   annotate("text",label="Treatment", color="Red",x=23,y=77,size=8)

3 个答案:

答案 0 :(得分:3)

另一种选择是使用点标记(而不是字母&#34; a&#34;)作为图例符号,您可以使用以下解决方法:

  1. 删除geom_text图例。
  2. 添加&#34;虚拟&#34;指向geom并将点标记大小设置为NA,因此实际上不会绘制任何点,但会生成图例。
  3. 覆盖图例中点标记的大小,以便点标记出现在图例键中以区分每个组。
  4. ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
      geom_text(size=8, show.legend=FALSE) + 
      geom_point(size=NA) +
      scale_color_manual(values=c("blue","red")) +
      theme_classic() +
      labs(colour="") +
      guides(colour=guide_legend(override.aes=list(size=4)))
    

    enter image description here

答案 1 :(得分:1)

作为快速修复,您可以通过对所需信息进行硬编码来调整图例键,但另一方面 - 保留密钥并删除标签。

library(grid)

GeomText$draw_key <- function (data, params, size) {
    txt <- ifelse(data$colour=="blue", "Control", "Treatment") 
    # change x=0 and left justify 
    textGrob(txt, 0, 0.5,  
             just="left", 
             gp = gpar(col = alpha(data$colour, data$alpha), 
                       fontfamily = data$family, 
                       fontface = data$fontface, 
                       # also added 0.5 to reduce size
                       fontsize = data$size * .pt* 0.5))
}

当您绘制时,您可以抑制图例标签,并使图例键更宽一些以适合文本。

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
   geom_text(size=8) + 
   scale_color_manual(values=c("blue","red")) +
   theme_classic() +
   theme(legend.text = element_blank(),
         legend.key.width = unit(1.5, "cm"))

答案 2 :(得分:1)

ggplot2 2.3.2 开头,您可以使用参数 key_glyph 指定图例中使用的字形:

ggplot(data, aes(x=x, y=y, label=ID, color=Group)) + 
  geom_text(size=8, key_glyph="point") + 
  scale_color_manual(values=c("blue", "red")) +
  labs(color=NULL) +
  theme_classic()

ggplot showing text legend with dot glyphs instead of the letter a

有关字形的完整列表,请参阅 ggplot2 documentation for draw_key。感谢 R Data Berlin 提醒我这个简单的解决方案。 Emil Hvitfeldt 也有一个 nice blog post showcasing the options

相关问题