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

时间:2015-11-17 19:47:33

标签: 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"))

1 个答案:

答案 0 :(得分:18)

您应该可以在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)

有关详细信息,请参阅?discrete_scale