Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add any geom_point shapes to ggplot legend?

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

set.seed(1)
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, !is.na(z)), mapping= aes(x, y, col= z)) +
  geom_point(data= subset(df, is.na(z)), mapping= aes(x, y), col= "black", shape= 4)

Heatmap

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 = is.na(z))) +
  scale_shape_manual(name = "Missing values", values=c(16, 4))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading