How to add any geom_point shapes to ggplot legend?

I make a heatmap within ggplot that looks something like that:

n <- 100
df <- data.frame(x= rnorm(n), y= rnorm(n), z= rnorm(n))
df$z[1:20] <- NA
ggplot() +
  geom_point(data= subset(df, !, mapping= aes(x, y, col= z)) +
  geom_point(data= subset(df,, mapping= aes(x, y), col= "black", shape= 4)


Here the points of the scatterplot change colours depending on values in z. Further, I added black crosses (shape 4) to visualize missings in z. I want to add the same x as in the plot to the legend saying missing above it. How can we do this?

>Solution :

I’d actually put the overall command in the same geom_point function using the shape parameter and then manually set the parameters with scale_shape_manual:

ggplot(df) +
  geom_point(aes(x, y, colour = z, shape = +
  scale_shape_manual(name = "Missing values", values=c(16, 4))

enter image description here

Leave a Reply