ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

scale_fill* doesn't see NaN as NA

Open cmcoffman opened this issue 10 years ago • 1 comments

Had some weirdness in my plots and eventually tracked it down. the <na.value> parameter in the various scale_fill* scales doesn't recognize <NaN> and instead fills them white.

Example:

# four points, top ones are NA and NaN
df <- data.frame(
  x = c(1, 2, 1, 2),
  y = c(1, 1, 2, 2),
  z = c(1, 2, NA, NaN)
)

# ggplot sees top left as NA and colors red,
# but the NaN on top right colors white (which
# is invisible if the background is white)
ggplot(df, aes(x, y)) +
  geom_point(aes(colour = z), size = 50) +
  scale_colour_gradient(na.value = "red")

image

I don't think this is the desired behavior.

It's also difficult to debug why this is happening because many R functions will put <NaN> where a user might expect <NA>. For example <mean(c(NA, NA), na.rm = TRUE)> returns <NaN>. I ran into this when doing some ddply on a large dataset. The problem was difficult to isolate because <all.equal()> can't always tell <NA> from <NaN>:

all.equal(
  a <- mean(c(NA, 10), na.rm = FALSE),
  b <- mean(c(NA, NA), na.rm = TRUE)
)

returns <TRUE>.

Also, while the View() function in Rgui will show <NaN> the View function in R-Studio will replace it with <NA>. The <write.csv()> function will also convert <NaN> to <NA>.

cmcoffman avatar Jan 11 '16 10:01 cmcoffman

This is definitely a bug

hadley avatar Jan 12 '16 00:01 hadley