首页 文章

关闭ggplot中的一些传说

提问于
浏览
176

假设我有一个带有多个图例的ggplot .

mov <- subset(movies, length != "")
(p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()
)

我可以关掉所有传说的显示:

(p1 <- p0 + theme(legend.position = "none"))

show_guide = FALSE 传递给 geom_point (根据this question)会关闭形状图例 .

(p2 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point(show_guide = FALSE)
)

但是,如果我想要关闭颜色图例呢?似乎没有办法告诉 show_guide 哪个图例应用其行为 . 对于尺度或美学,没有 show_guide 论证 .

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  scale_colour_discrete(show_guide = FALSE) +
  geom_point()
)
# Error in discrete_scale

(p4 <- ggplot(mov, aes(year, rating, shape = mpaa)) +
  aes(colour = length, show_guide = FALSE) +
  geom_point()
)
#draws both legends

This question表明现代(自ggplot2 v0.9.2)控制图例的方式是 guides 函数 .

我希望能够做类似的事情

p0 + guides(
  colour = guide_legend(show = FALSE) 
)

guide_legend 没有show参数 .

如何指定显示哪些图例?

2 回答

  • 237

    您只需将 show.legend=FALSE 添加到geom即可抑制相应的图例

  • 4

    您可以在 scale_..._...() 中使用 guide=FALSE 来抑制图例 .

    对于您的示例,您应该使用 scale_colour_continuous() ,因为 length 是连续变量(非离散) .

    (p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
       scale_colour_continuous(guide = FALSE) +
       geom_point()
    )
    

    或者使用函数 guides() ,您应该为不希望显示为图例的元素/美学设置 FALSE ,例如, fillshapecolour .

    p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
      geom_point()    
    p0+guides(colour=FALSE)
    

    更新

    两个提供的解决方案都在新的 ggplot2 版本2.0.0中工作,但此库中不再存在 movies 数据集 . 相反,您必须使用新包 ggplot2movies 来检查这些解决方案 .

    library(ggplot2movies)
    data(movies)
    mov <- subset(movies, length != "")
    

相关问题