我试图强制ggplot显示图例并修复某个因子的颜色,即使在某个范围内没有值。
在下面的可重现示例中,图1在变量X1的每个范围内至少有一个值,并根据需要绘制。将打印每个图例标签,并与所需的颜色相匹配。
在示例2中,变量Y1在创建的每个范围中都没有值。因此,绘图仅显示前4个图例标签,并使用前4种颜色。
有没有一种方法来绘制这个图,强制cat2显示所有八个图例标签,并修复颜色,使ggplot的值始终为红色,ggplot的值始终为蓝色,等等。
我试过所有我能想到的东西,但都没有成功。
--可重现的例子--
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"))
发布于 2015-11-18 03:55:01
您应该能够在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
https://stackoverflow.com/questions/33765710
复制相似问题