Assign ggplot legend to show all categories if no values

I am trying to get ggplot to show the legend and correct the colors for the factor, even if there is no value in the range.

In the reproducibility example below in FIG. 1, there is at least one value in each range of the variable X1 and graphics as desired. Each legend label is plotted on the chart and corresponds to the desired color.

In Example 2, the variable Y1 does not matter in each of the created ranges. As a result, only the first 4 legend labels are displayed on the chart and the first 4 colors are used.

Is there a way to build this drawing that forces ggplot to display 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 that I can think of without success.

- Playable 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")) 
+8
r ggplot2
source share
1 answer

You can use drop = FALSE inside scale_fill_manual . I.e

 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) 

See ?discrete_scale for more information.

+8
source share

All Articles