2014-10-08 20 views
2

我的问题是我想要在散点图上叠加一个散点图,并且这两个图的颜色会随着一个变量而变化。我只想保留只有一种颜色的传说。如果我使用scale_colour_discrete(guide = "none")他们都将消失。从传说中生成的传说中删除一个aes,共享常见的aes名称

重复的例子是:

library(reshape2) 

iris2 <- melt(iris, id.var = "Species") 

ggplot(iris2, aes(x = variable, y = value, group = Species)) + 
    geom_point(aes(color = ifelse(value < 3, "type1", "type2"))) + 
    geom_line(aes(color = Species)) 

我只是想显示“物种”,而不是类型的传说。

回答

4

设置在geom_point层show_guide=FALSE

ggplot(iris2, aes(x = variable, y = value, group = Species)) + 
    geom_point(aes(color = ifelse(value < 3, "type1", "type2")), show_guide=FALSE) + 
    geom_line(aes(color = Species)) + 
    scale_colour_discrete("Species", breaks=levels(iris2$Species)) 

enter image description here

+0

这就是答案。 +1 – 2014-10-09 18:03:44

+0

我向主人鞠躬。 – eipi10 2014-10-10 07:36:40

2

我不知道当两者都被绑在相同的美学上时,你是否可以摆脱只有一部分传奇。但是这里有一个解决方法:使用fill审美为您的点,然后摆脱fill美学的传奇。在geom_point中设置color=NA摆脱每个点周围的边框颜色(默认为黑色)。您还需要使用具有单独边框和填充的标记样式。有关可用样式,请参阅?pch

library(reshape2) 
library(ggplot2) 

iris2 = melt(iris, id.var = "Species") 

ggplot(iris2, aes(x = variable, y = value, group = Species)) + 
    geom_point(aes(fill = ifelse(value < 3, "type1", "type2")), 
      pch=21, color=NA) + 
    geom_line(aes(color = Species)) + 
    guides(fill=FALSE) 

enter image description here

+1

THX!但我认为'ggplot2'有更好的选择来指定这个'aes'来自哪里 – MYjx 2014-10-09 00:30:07

0

这也是一个技巧,但更推广到其他美观。它涉及倾销美学,你不想做一个你想要的传说。然后抓住那个传说。接下来你绘制你想要的图表而没有图例。愚蠢的利润。在你想要的情节上注释你想要的传说。

library(reshape2) 
library(gtable) 

iris2 <- melt(iris, id.var = "Species") 
myplot <-ggplot(iris2, aes(x = variable, y = value, group = Species)) + 
    # geom_point(aes(color = ifelse(value < 3, "type1", "type2"))) + 
    geom_line(aes(color = Species)) 

legend_line <- grobTree(gtable_filter(ggplot_gtable(ggplot_build(myplot)), "guide-box")) 

ggplot(iris2, aes(x = variable, y = value, group = Species)) + 
    geom_point(aes(color = ifelse(value < 3, "type1", "type2"))) + 
    geom_line(aes(color = Species)) + 
    guides(color=FALSE) + 
    theme(plot.margin=unit(c(1,4,1,1),"cm")) + 
    annotation_custom(grob = legend_line, xmin = 4, xmax = 6.5, 
     ymin = 3.5, ymax = 4.5) 

enter image description here