首页 文章

删除图例ggplot 2.2

提问于
浏览
155

我试图保持一层的图例(平滑)并删除另一层(点)的图例 . 我试过用 guides(colour = FALSE)geom_point(aes(color = vs), show.legend = FALSE) 来关闭传说 .

Edit :由于这个问题及其答案很受欢迎,因此可重现的例子依次为:

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

enter image description here

4 回答

  • 329

    可能还有另一个解决方案:
    你的代码是:

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

    您可以在 aes 调用后指定 show.legend 参数:

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

    然后相应的图例应该消失

  • 8

    r cookbook,其中bp是你的ggplot:

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

    bp + guides(fill=FALSE)
    

    在指定比例时也可以这样做:

    bp + scale_fill_discrete(guide=FALSE)
    

    这将删除所有图例:

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

    如果您的图表同时使用 fillcolor 美学,则可以删除图例:

    + guides(fill=FALSE, color=FALSE)
    
  • 44

    作为问题和 user3490026 's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the 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()
    

    enter image description here

    Remove all legends: @user3490026

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

    Remove all legends: @duhaime

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

    Turn off legends: @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()
    

    Remove fill so that linetype becomes visible

    p + guides(fill = FALSE)
    

    Same as above via the scale_fill_ function:

    p + scale_fill_discrete(guide = FALSE)
    

    现在可以回答OP的要求

    “保持一层的图例(平滑)并删除另一层的图例(点)”

    Turn some on some off ad-hoc post-hoc

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

    enter image description here

相关问题