我试图保持一个层的图例(平滑),并删除另一个层的图例(点)。我已经尝试用指南(color = FALSE)和geom_point(aes(color = vs), show关闭传说。legend = FALSE)。

编辑:由于这个问题及其答案很受欢迎,下面是一个可重复的例子:

library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) + 
theme_bw() 


当前回答

从烹饪书中,bp是你的ggplot:

删除特定美学的图例(填充):

bp + guides(fill="none")

它也可以在指定比例时完成:

bp + scale_fill_discrete(guide="none")

这将删除所有的传说:

bp + theme(legend.position="none")

其他回答

由于问题和user3490026的答案是热门搜索,所以我制作了一个可重复的示例,并简要说明了迄今为止提出的建议,以及明确解决OP问题的解决方案。

One of the things that ggplot2 does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear) appears twice, once for linetype and once for fill, resulting in a combined legend. By contrast, gear has its own legend entry as it is not treated as the same as factor(gear). The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.

# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) + 
theme_bw() 

删除所有图例:@user3490026

p + theme(legend.position = "none")

删除所有图例:@duhaime

p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)

关闭传说:@Tjebo

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) + 
theme_bw() 

删除填充,使线条变得可见

p + guides(fill = FALSE)

如上所述,通过scale_fill_函数:

p + scale_fill_discrete(guide = FALSE)

现在有一个可能的答案

,以保持图例的一层(平滑)和删除图例 其他(点)”

打开一些,关闭一些,临时的,事后的

p + guides(fill = guide_legend(override.aes = list(color = NA)), 
           color = FALSE, 
           shape = FALSE)  

如果你的图表同时使用填充和颜色美学,你可以删除图例:

+ guides(fill=FALSE, color=FALSE)

也许还有另一种解决方案: 你的代码是:

geom_point(aes(..., show.legend = FALSE))

您可以指定show。aes调用后的图例参数:

geom_point(aes(...), show.legend = FALSE)

然后相应的图例应该消失

从烹饪书中,bp是你的ggplot:

删除特定美学的图例(填充):

bp + guides(fill="none")

它也可以在指定比例时完成:

bp + scale_fill_discrete(guide="none")

这将删除所有的传说:

bp + theme(legend.position="none")