1

I have a data.frame which I'd like to scatter plot using ggplot. The data have 3 factors whose levels I'd like to show in the legend, although the color of the points will only be according to one of these factors (df$group below).

Here's what I have so far:

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))

I manually specify colors:

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]

This is what I have for showing the 3 factors in the legend (df$group and df$type):

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

So my question is how to get background.colors appear in the legend under "background" rather than the gray scale colors chosen by default that currently appear there.

dan
  • 6,048
  • 10
  • 57
  • 125
  • this may be helpful http://stackoverflow.com/questions/41390181/ggplot2-add-separate-legend-each-for-two-y-axes-in-facet-plot – Sathish Mar 25 '17 at 08:54
  • Do I understand it correctly that you want to have a grouped color legend? Because if you simply want a third legend you could use width or alpha. – takje Mar 25 '17 at 09:08
  • Not sure what a grouped legend is. What I want is simply to have the levels of df$background with background.colors and the title "background" appear in the legend below that of group. – dan Mar 25 '17 at 15:36

1 Answers1

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

kdauria
  • 6,300
  • 4
  • 34
  • 53
dan
  • 6,048
  • 10
  • 57
  • 125