删除 ggplot2 中的额外图例 [英] Remove extra legends in ggplot2
问题描述
我有一个简单的数据框,我正在尝试使用 ggplot2
绘制组合线图和点图.假设我的数据如下所示:
I have a simple data frame that I'm trying to do a combined line and point plot using ggplot2
. Supposing my data looks like this:
df <- data.frame(x=rep(1:10,2), y=c(1:10,11:20),
group=c(rep("a",10),rep("b",10)))
我正在尝试制作一个情节:
And I'm trying to make a plot:
g <- ggplot(df, aes(x=x, y=y, group=group))
g <- g + geom_line(aes(colour=group))
g <- g + geom_point(aes(colour=group, alpha = .8))
g
结果看起来不错,但有一个例外.它有一个额外的图例,显示了我的 geom_point
层的 alpha
.
The result looks fine with one exception. It has an extra legend showing the alpha
for my geom_point
layer.
如何让图例显示组颜色,而不是显示我的 alpha 设置的颜色?
How can I keep the legend showing group colors, but not the one that shows my alpha settings?
推荐答案
美学可以在 ggplot
调用中设置或映射.
Aesthetics can be set or mapped within a ggplot
call.
aes(...)
中定义的美学是从数据中映射,并创建一个图例.- 美学也可以设置为单个值,方法是在
aes()
之外定义它.
- An aesthetic defined within
aes(...)
is mapped from the data, and a legend created. - An aesthetic may also be set to a single value, by defining it outside
aes()
.
在这种情况下,您似乎希望 set alpha = 0.8
和 map colour = group
.
In this case, it appears you wish to set alpha = 0.8
and map colour = group
.
要做到这一点,
将 alpha = 0.8
放在 aes()
定义之外.
Place the alpha = 0.8
outside the aes()
definition.
g <- ggplot(df, aes(x = x, y = y, group = group))
g <- g + geom_line(aes(colour = group))
g <- g + geom_point(aes(colour = group), alpha = 0.8)
g
对于任何映射变量,您可以通过在适当的scale_...
中使用guide = 'none'
来抑制图例的出现称呼.例如.
For any mapped variable you can supress the appearance of a legend by using guide = 'none'
in the appropriate scale_...
call. eg.
g2 <- ggplot(df, aes(x = x, y = y, group = group)) +
geom_line(aes(colour = group)) +
geom_point(aes(colour = group, alpha = 0.8))
g2 + scale_alpha(guide = 'none')
哪个将返回相同的情节
编辑@Joran 的评论很准确,我的回答更全面
EDIT @Joran's comment is spot-on, I've made my answer more comprehensive
这篇关于删除 ggplot2 中的额外图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!