我想知道如何在NA
中获取scale_fill_brewer
值的图例类别。这是我的MWE。
set.seed(12345)
dat <-
data.frame(
Row = rep(x = LETTERS[1:5], times = 10)
, Col = rep(x = LETTERS[1:10], each = 5)
, Y = c(rnorm(n = 48, mean = 500, sd = 1), NA, NA)
)
dat$Y1 <- addNA(cut(log(dat$Y), 5))
levels(dat$Y1)
[1] "(6.21,6.212]" "(6.212,6.214]" "(6.214,6.216]" "(6.216,6.218]" "(6.218,6.22]" NA
library(ggplot2)
ggplot(data = dat, aes(x = Row, y = Col)) +
geom_tile(aes(fill = Y1), colour = "white") +
scale_fill_brewer(palette = "PRGn")
答案 0 :(得分:1)
您可以明确将缺失的值视为Y1
因素的另一个级别,以便将其添加到您的图例中。
像以前一样切割变量后,您需要将NA
添加到因子的级别。在这里,我将其添加为最后一级。
dat$Y1 <- cut(log(dat$Y), 5)
levels(dat$Y1) <- c(levels(dat$Y1), "NA")
然后将所有缺失值更改为字符串NA
。
dat$Y1[is.na(dat$Y1)] <- "NA"
答案 1 :(得分:1)
我在没有更改原始数据框的情况下找到了变通方法,根据此post添加了额外的图例:
ggplot(data = dat, aes(x = Row, y = Col)) +
geom_tile(aes(fill = Y1), colour = "white") +
scale_fill_brewer(palette = "PRGn")+
geom_point(data = dat, aes(size="NA"), shape =NA, colour = "grey95")+
guides(size=guide_legend("NA", override.aes=list(shape=15, size = 10)))
为NA着色:
ggplot(data = dat, aes(x = Row, y = Col)) +
geom_tile(aes(fill = Y1), colour = "white") +
scale_fill_brewer(palette = "PRGn", na.value="red")+
geom_point(data = dat, aes(size="NA"), shape =NA, colour = "red")+
guides(size=guide_legend("NA", override.aes=list(shape=15, size = 10)))