简体   繁体   English

na.value 不能在 r 中的 scale_fill_continuous() 中工作

[英]na.value can not work in scale_fill_continuous() in r

I want to set the color of NA value.我想设置 NA 值的颜色。

But it does not work when I set scale_fill_continuous(na.value = 'red') .但是当我设置scale_fill_continuous(na.value = 'red')时它不起作用。

Reproducible example like this:像这样可重现的例子:

df = data.frame(
  grade = c('class 1', 'class 1', 'class 2'),
  sex   = c('Female', 'Male', 'Female'),
  n     = c(1,5,3))
df

df %>% ggplot(aes(x = sex, y = grade, fill = n)) +
  geom_tile()

df %>% ggplot(aes(x = sex, y = grade, fill = n)) +
  geom_tile() +
  scale_fill_continuous(na.value = 'red')

Any help will be highly appreciated!任何帮助将不胜感激!

There is no NA value in the data, you need to first generate it and then use the plotting code.数据中没有NA值,需要先生成再使用绘图代码。

One way to generate the missing combination is to use tidyr::complete .生成缺失组合的一种方法是使用tidyr::complete

library(ggplot2)

tidyr::complete(df, grade, sex) %>%
  ggplot(aes(x = sex, y = grade, fill = n)) +
  geom_tile() + 
  scale_fill_continuous(na.value = 'red')

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM