ggplot2 fill and colour mapping legend

Viewed 1539

I have a sample data frame with four variables and I'm trying to map h variable to fill and s variable to shape. Since my s variable can take only two values (either 'f' or 'u') I want to use geom_point 24 and 21 which can take fill and colour argument.

library(ggplot2)
h <- c(1,2,3,4,5)
x <- seq(1:5)
y <- c(1,3,3,5,5)
s <- c(rep('f',3),rep('u',2))
dt <- data.frame(h,x,y,s)

Ideally, my geom_point would have black outline and coloured fill. I can plot this with the below code and it produces this plot:

ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(fill = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(24, 21))

colours controlled by fill

I cannot get legend to display coloured keys since colour of legend key is mapped to colour not to fill.

I can have coloured legend keys if I change my geom_point to 19 and 17 and map my h variable colour:

ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(colour = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(19, 17))

colours controlled by colour

Legend is displayed with coloured keys but black outline on my points on plot is gone.

Is there any way to choose what is mapped on legend key (fill or colour) if I used both fill and colour for geom_point?

1 Answers
ggplot(dt, aes(x=y, y=x)) +  
    geom_point(mapping = aes(fill = factor(h), shape = s), size = 5) +
    scale_shape_manual(values = c(24, 21)) +
    guides(fill=guide_legend(override.aes=list(shape=21)))

Above code produces this plot - exactly as I wanted, credits to bdemarest

fill mapped to legend

Related