r - 强制 ggplot 图例在没有值时显示所有类别

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

最佳答案

您应该能够在 scale_fill_manual 中使用 drop = FALSE。也就是说,

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

关于r - 强制 ggplot 图例在没有值时显示所有类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709451/

相关文章:

r - 考虑到位置为 ='dodge' 的条形,如何在柱形条形图上添加线条,其中线条经过条形的中顶部?

r - 使用 ggplot2 : Code produces straight line at 0 在直方图上绘制正态曲线

r - 根据数据集中的列对图中的分面进行排序

r - geom_polygon 的渐变填充

r - igraph 中的 assortativity.nominal

r - 在 R 中,如何在单个设备中放置多个 filled.contour() 图?

r - 将月份第一级的值保留在数据框中,同时将 R 中的其余值设置为零

r - mgcv 中基于张量积的高斯过程更平滑

r - 在ggplot2中强制密度图的颜色

r - 我不明白函数内的错误 "object not found"