2014-10-08 21 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