Scatterplot: Show missing factor level(s) in legend

I want to create a scatterplot + legend, using a grouping variable ("category") in the example below. How can I force all factor levels (i.e., LETTERS[1:5] below) , even if missing in the actual data, to show up in the legend (to stress their absence!):

dat <- data.frame(V1 = sample(seq(1:10), 10),
              V2 = sample(seq(1:10), 10),
              category = factor(sample(LETTERS[1:4], 10, replace=TRUE),
                  LETTERS[1:5]))

ggplot(dat, aes(x=V1, y=V2)) +
    geom_point(aes(size=category), shape=1)

In my actual script, I use scale_size_discrete() to change the legend labels etc.

Thank you!

Answers


Use scale_size_discrete() and add argument drop=FALSE to show all levels.

ggplot(dat, aes(x=V1, y=V2)) +
  geom_point(aes(size=category), shape=1)+
  scale_size_discrete(drop=FALSE)

Need Your Help

Determine if a 3D point is within a triangle

3d geometry

Given a 3D point (x, y &amp; z), and a triangle made of three other 3D points, how can I determine if the point is in triangle?