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

Fla*_*ion 9 r legend ggplot2

示例代码和图:

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")))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

我试过了:

geom_text(show_guide = F)
Run Code Online (Sandbox Code Playgroud)

但这完全取消了传说.

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

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)
Run Code Online (Sandbox Code Playgroud)

eip*_*i10 5

另一种选择是使用点标记(而不是字母“ a”)作为图例符号,您可以通过以下变通办法来实现:

  1. 删除geom_text图例。
  2. 添加一个“虚拟”点几何,并将点标记大小设置为NA,这样实际上不会绘制任何点,但是会生成一个图例。
  3. 覆盖图例中点标记的大小,以便点标记将出现在图例键中以区分每个组。

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)))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


use*_*650 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))
}
Run Code Online (Sandbox Code Playgroud)

当您绘图时,您会抑制图例标签,并使图例键更宽以适应文本。

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"))
Run Code Online (Sandbox Code Playgroud)