Richard
Richard

Reputation: 61289

ggplot suppresses NA colouring

I am trying to use ggplot to plot a geom_raster with scale_fill_fermenter. I'm using R v4.0.2 and ggplot <3.3.2.

I would like my NA values to show up as dark grey or black, but scale_fill_fermenter seems to be dropping the NAs while scale_fill_gradient, which I would prefer not to use, retains them.

That is I want the look for this (from scale_fill_gradient):

scale_fill_gradient with NAs

but using scale_fill_fermenter I get this:

scale_fill_fermenter with NAs

How can I fix this?

A MWE:

library(ggplot2)

dat = read.csv(text="a,b,c\n100,1000,NA\n500,1000,NA\n1000,500,0.10817004452149229\n1000,100,0.0930867799644483\n100,100,0.033891940293246624\n500,100,0.0784308558280871\n100,500,0.07515759043562542\n1000,1000,NA\n500,500,0.10275381878402282\n")
dat$a = as.factor(dat$a)
dat$b = as.factor(dat$b)

p = ggplot(dat, aes(x = b, y = a)) + 
  geom_raster(aes(fill=c)) + 
  geom_label(aes(label=round(c,digits=1)), fill="white", fontface="bold", label.size=0, label.padding = unit(0.1, "lines")) +
  scale_fill_gradient(low="#fee8c8", high="red") 

print(p)

ggsave("/z/out1.png", p)

p = ggplot(dat, aes(x = b, y = a)) + 
  geom_raster(aes(fill=c)) + 
  geom_label(aes(label=round(c,digits=1)), fill="white", fontface="bold", label.size=0, label.padding = unit(0.1, "lines")) +
  scale_fill_fermenter(type="seq", palette="Reds", direction=1, na.value = "black")

print(p)

ggsave("/z/out2.png", p)

Upvotes: 1

Views: 83

Answers (1)

nniloc
nniloc

Reputation: 4243

This NA values are displayed correctly (as black) when I run this with R 4.0.2 and ggplot2 3.3.2.

Updating to the latest version of ggplot2 using update.packages() will fix this.

Upvotes: 1

Related Questions