Home > Back-end >  Error in geom_bar plot: Must request at least one colour from a hue palette
Error in geom_bar plot: Must request at least one colour from a hue palette

Time:03-19

Why am I getting this error with the following code while working through Wickham & Grolemund, 2016 (R for Data Science):

library(tidyverse)
ggplot(data = diamonds)  
geom_bar(mapping = aes(x = cut, color = clarity, fill = NA),
position = "identity")

The error reads: Must request at least one colour from a hue palette

The code gives the expected output when it is run as follows:

library(tidyverse)
ggplot(data = diamonds,
mapping = aes(x = cut, color = clarity)
)  
geom_bar(fill = NA, position = "identity")

Where am I getting it wrong?

CodePudding user response:

I'm not sure whether this is expected behaviour here or not.

If you want the bars to be unfilled, you should put the argument fill = NA outside the aes call. For example, the following works fine:

ggplot(data = diamonds)  
geom_bar(mapping = aes(x = cut, color = clarity), fill = NA, position = "identity")

enter image description here

Things are more complicated when you put the NA inside the aes call, because if you use a single value (like NA) as an aesthetic mapping, ggplot internally creates a whole column of NA values in its internal data frame and maps the aesthetic to that. That doesn't matter too much if you have a continuous color scale; in fact, your code works fine if you specify that you want a 'numeric-flavoured' NA:

ggplot(data = diamonds)  
geom_bar(mapping = aes(x = cut, color = clarity, fill = NA_real_),position = "identity")

enter image description here

Note though that rather than the fill = NA_real_ being interpreted as 'no fill', it is interpreted as 'fill with the default NA colour`, which is gray.

If you have a discrete type of NA such as NA_character_ or just plain old NA (which is of class 'logical'), you get the error because when ggplot tries to set up the fill scale, it counts the number of unique non-NA values to fetch from its discrete color palette. It is the palette function that complains and throws an error when you ask it for 0 colours. In fact, the simplest code that replicates your error is:

scales::hue_pal()(0)
#> Error: Must request at least one colour from a hue palette.

The behaviour of ggplot has changed since 2016 when the tutorial you are following was written, so you would need to look back in the change log to see whether this was an intentional change, but the bottom line is that fill = NA should be used outside aes if you want the bars to be unfilled.

  •  Tags:  
  • r
  • Related