由于问题和 user3490026 的回答是热门搜索,我制作了一个可重复的示例,并简要说明了迄今为止提出的建议,以及明确解决 OP 问题的解决方案问题。
ggplot2 所做的一件可能令人困惑的事情是,当它们与同一个变量相关联时,它会自动混合某些图例。例如,factor(gear) 出现两次,一次为linetype,一次为fill,从而形成一个组合图例。相比之下,gear 有自己的图例条目,因为它与factor(gear) 不同。到目前为止提供的解决方案通常效果很好。但有时,您可能需要覆盖指南。请参阅底部的最后一个示例。
# 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)
现在是对 OP 要求的一种可能答案
"保持一层的图例(平滑),去掉一层的图例
其他(点)”
临时开启一些关闭
p + guides(fill = guide_legend(override.aes = list(color = NA)),
color = FALSE,
shape = FALSE)