r - Force ggplot legend to show all categories when no values are present -
this question has answer here:
i trying force ggplot show legend , fix colors factor if no value in range present.
in reproducible example below, figure 1 has @ least 1 value in each range of variable x1 , plots desired. each legend label plotted , matches desired color.
in example 2, variable y1 not have value in each of ranges created. result, plot shows first 4 legend labels , uses first 4 colors.
is there way plot figure forces ggplot show 8 legend labels , fix colors cat1 values red, cat2 values blue, etc.
i have tried 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"))
you should able use drop = false within scale_fill_manual. 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
Comments
Post a Comment