关闭 ggplot 中的一些图例 [英] Turning off some legends in a ggplot
问题描述
假设我有一个包含多个图例的 ggplot.
Suppose I have a ggplot with more than one legend.
mov <- subset(movies, length != "")
(p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
)
我可以像这样关闭所有图例的显示:
I can turn off the display of all the legends like this:
(p1 <- p0 + theme(legend.position = "none"))
将 show_guide = FALSE
传递给 geom_point
(根据 这个问题) 关闭形状图例.
Passing show_guide = FALSE
to geom_point
(as per this question) turns off the shape legend.
(p2 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point(show_guide = FALSE)
)
但是如果我想关闭颜色图例呢?似乎没有办法告诉 show_guide
要将其行为应用于哪个图例.并且没有关于尺度或美学的 show_guide
论据.
But what if I want to turn off the colour legend instead? There doesn't seem to be a way of telling show_guide
which legend to apply its behaviour to. And there is no show_guide
argument for scales or aesthetics.
(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
这个问题表明现代(自 ggplot2 v0.9.2 起)方式使用 guides
功能控制图例.
This question suggests that the modern (since ggplot2 v0.9.2) way of controlling legends is with the guides
function.
我希望能够做类似的事情
I want to be able to do something like
p0 + guides(
colour = guide_legend(show = FALSE)
)
但是 guide_legend
没有显示参数.
but guide_legend
doesn't have a show argument.
如何指定显示哪些图例?
How do I specify which legends get displayed?
推荐答案
你可以在 scale_..._...()
中使用 guide=FALSE
来抑制传奇.
You can use guide=FALSE
in scale_..._...()
to suppress legend.
对于您的示例,您应该使用 scale_colour_continuous()
因为 length
是连续变量(不是离散的).
For your example you should use scale_colour_continuous()
because length
is continuous variable (not discrete).
(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_continuous(guide = FALSE) +
geom_point()
)
或者使用函数 guides()
你应该为你不想显示为图例的元素/美学设置 FALSE
,例如,fill
、形状
、颜色
.
Or using function guides()
you should set FALSE
for that element/aesthetic that you don't want to appear as legend, for example, fill
, shape
, colour
.
p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
p0+guides(colour=FALSE)
更新
提供的两种解决方案都适用于新的 ggplot2
2.0.0 版,但此库中不再存在 movies
数据集.相反,您必须使用新包 ggplot2movies
来检查这些解决方案.
UPDATE
Both provided solutions work in new ggplot2
version 2.0.0 but movies
dataset is no longer present in this library. Instead you have to use new package ggplot2movies
to check those solutions.
library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")
这篇关于关闭 ggplot 中的一些图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!