强制ggplot图例显示没有值时的所有类别

lea*_*rer 17 r ggplot2

我试图强制ggplot显示图例并修复因子的颜色,即使范围内没有值存在.

在下面的可再现的示例中,图1在变量X1的每个范围中具有至少一个值并且根据需要绘制.绘制每个图例标签并匹配所需的颜色.

在示例2中,变量Y1在每个创建的范围中没有值.因此,该图仅显示前4个图例标签并使用前4种颜色.

有没有办法绘制这个图形,迫使ggplot显示所有八个图例标签并修复颜色,以便cat1值始终为红色,cat2值始终为蓝色等.

我已经尝试了所有我能想到的但没有成功的事情.

- 可重复的例子 -

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"))
Run Code Online (Sandbox Code Playgroud)

Jas*_*lns 21

你应该能够在drop = FALSE内部使用scale_fill_manual.那是,

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)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅 ?discrete_scale