保留标签的同时删除ggplot图例符号 [英] Removing ggplot legend symbol while retaining label

查看:82
本文介绍了保留标签的同时删除ggplot图例符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码和图形:

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")))

我要解决的是删除图例符号("a")并为组标签(控制"和处理")中出现的图形分别着色(分别为蓝色和红色).

What I'm trying to solve is removing the legend symbols (the "a") and coloring the Group labels (Control and Treatment) as they appear in the plot (Blue and Red respectively).

我尝试过:

geom_text(show_guide = F)

但这只是完全删除了图例.

But that just removes the legend entirely.

为简单起见,我可以使用注解...但想知道是否有图例专用解决方案.

To keep it simple I could just use annotate...but wondering if there's a legend specific solution.

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)

推荐答案

作为一种快速解决方案,您可以通过对所需信息进行硬编码来调整图例密钥,尽管反之亦然-保留密钥并除去标签.

As a quick fix you can tweak the legend key, by hard coding the info you want, although around the other way - keep the key and remove the label.

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))
}

当您进行绘图时,将隐藏图例标签,并使图例键更宽以适合文本.

And when you plot you suppress the legend labels, and make legend key a bit wider to fit text.

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"))

这篇关于保留标签的同时删除ggplot图例符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆