简体   繁体   中英

Error in geom_bar plot: Must request at least one colour from a hue palette

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?

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")

在此处输入图像描述

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")

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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