2017-03-25 60 views
1

我有一個data.frame我想散點圖使用ggplot。 這些數據有3 factors我想在圖例中顯示其級別,但點的顏色只會根據其中一個因素(下面的df$group)。Ggplot與兩個以上的傳說

這是我到目前爲止有:

set.seed(1) 
df <- data.frame(x=rnorm(100),y=rnorm(100), 
       group=LETTERS[sample(5,100,replace=T)], 
       type=letters[sample(3,100,replace=T)], 
       background=sample(4,100,replace=T),stringsAsFactors=F) 

df$group <- factor(df$group,LETTERS[1:5]) 
df$type <- factor(df$type,;etters[1:3]) 
df$background <- factor(df$background,c(1:4)) 

我手動指定顏色:

require(RColorBrewer) 
require(scales) 
all.colors <- hcl(h=seq(0,(12-1)/(12),length=12)*360,c=100,l=65,fixup=TRUE) 
group.colors <- all.colors[1:5] 
type.colors <- all.colors[6:8] 
background.colors <- all.colors[9:12] 

這就是我對顯示圖例(df$groupdf$type)3 factors

require(ggplot2) 

ggplot(df,aes(x=x,y=y,colour=group,fill=type,alpha=background))+geom_point(cex=2,shape=1,stroke=1)+ 
    theme_bw()+theme(strip.background=element_blank())+scale_color_manual(drop=FALSE,values=group.colors,name="group")+ 
    guides(fill=guide_legend(override.aes=list(colour=type.colors,pch=0))) 

enter image description here

所以我的問題是如何讓background.colors出現在「背景」下的圖例中,而不是默認情況下選擇的當前出現在那裏的灰度色。

+0

這可能會有幫助http://stackoverflow.com/questions/41390181/ggplot2-add-separate-legend-each-for-two-y-axes-in-facet-plot – Sathish

+0

我是否正確理解您想要分組的顏色圖例?因爲如果你只是想要第三個圖例,你可以使用寬度或alpha。 – takje

+0

不確定分組的圖例是什麼。我想要的僅僅是讓背景顏色的df $背景以及標題「背景」出現在組下方的圖例中。 – dan

回答

0
ggplot(df,aes(x=x, y=y, colour=group, fill=type, alpha=background))+ 
    geom_point(cex=2, shape=1, stroke=1) + 
    theme_bw() + 
    theme(strip.background=element_blank()) + 
    scale_color_manual(drop=FALSE, values=group.colors, name="group") + 
    guides(fill=guide_legend(override.aes=list(colour=type.colors,pch=0)), 
     alpha=guide_legend(override.aes=list(colour=background.colors,pch=0))) 

enter image description here