ggplot2:scale_fill_brewer中NA的图例 [英] ggplot2: Legend for NA in scale_fill_brewer
问题描述
我想知道如何在 scale_fill_brewer
中获得 NA
值的图例类别。这是我的MWE。
pre $ set $ se $(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),color =white)+
scale_fill_brewer(palette =PRGn)
p>你可以明确地将缺失的值作为你的
Y1
因子的另一个等级来获取它在你的图例中。 在像之前一样剪切变量之后,您会希望将 NA
添加到该因子的级别。
dat $ Y1 < - cut(log(dat $ Y),5)
等级(dat $ Y1)<-c(等级(dat $ Y1),NA)
然后将所有缺少的值更改为字符串 NA
。
这使得图中的 NA
图例的一部分:
I wonder how I can get legend category for NA
values in scale_fill_brewer
. Here is my 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")
You could explicitly treat the missing values as another level of your Y1
factor to get it on your legend.
After cutting the variable as before, you will want to add NA
to the levels of the factor. Here I add it as the last level.
dat$Y1 <- cut(log(dat$Y), 5)
levels(dat$Y1) <- c(levels(dat$Y1), "NA")
Then change all the missing values to the character string NA
.
dat$Y1[is.na(dat$Y1)] <- "NA"
This makes NA
part of the legend in your plot:
这篇关于ggplot2:scale_fill_brewer中NA的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!