Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force ggplot legend to show all categories when no values are present [duplicate]

Tags:

I am trying to force ggplot to show the legend and fix the colors for a factor even if no value in a range is present.

In the reproducible example below, Figure 1 has at least one value in each range of the variable X1 and plots as desired. Each legend label is plotted and matches the desired color.

In example 2, the variable Y1 does not have a value in each of the ranges that are created. As a result, the plot only shows the first 4 legend labels and uses the first 4 colors.

Is there a way to plot this figure that forces ggplot to show all eight legend labels and fix the colors so that cat1 values are always red, cat2 values are always blue, etc.

I have tried everything I can think of without success.

-- Reproducible example --

set.seed(45678) dat <- data.frame(Row = rep(x = LETTERS[1:5], times = 10),                    Col = rep(x = LETTERS[1:10], each = 5),                   Y = rnorm(n = 50, mean = 0, sd = 0.5),                   X = rnorm(n = 50, mean = 0, sd = 2))  library(ggplot2) library(RColorBrewer) library(dplyr)  dat <- dat %>% mutate(Y1 = cut(Y, breaks = c(-Inf,-3:3,Inf)),                       X1 = cut(X, breaks = c(-Inf,-3:3,Inf)))  # Figure 1 ggplot(data =  dat, aes(x = Row, y = Col)) +   geom_tile(aes(fill = X1), color = "black") +   scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),                     labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8"))  # Figure 2 ggplot(data =  dat, aes(x = Row, y = Col)) +   geom_tile(aes(fill = Y1), color = "black") +   scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),                     labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8")) 
like image 291
learnmorer Avatar asked Nov 17 '15 19:11

learnmorer


1 Answers

You should be able to use drop = FALSE within scale_fill_manual. That is,

ggplot(data =  dat, aes(x = Row, y = Col)) +   geom_tile(aes(fill = Y1), color = "black") +   scale_fill_manual(values = c("red", "blue", "green", "purple", "pink", "yellow", "orange", "blue"),                     labels = c("cat1", "cat2", "cat3", "cat4", "cat5", "cat6", "cat7", "cat8"),                      drop = FALSE) 

For more information, see ?discrete_scale

like image 124
JasonAizkalns Avatar answered Sep 18 '22 04:09

JasonAizkalns