Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatterplot: Show missing factor level(s) in legend

Tags:

r

ggplot2

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!

like image 470
mrcalvin Avatar asked Jan 30 '14 16:01

mrcalvin


1 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)
like image 177
Didzis Elferts Avatar answered Oct 30 '22 16:10

Didzis Elferts