0
library(tidyverse)
df <- tibble(col1 = as.Date(c("2020-01-01", "2020-01-01", "2020-02-01", 
                              "2020-02-01")),
             col2 = c("A", "B", "A", "B"),
             col3 = c(8, 3, 2, 9))
#> # A tibble: 4 x 3
#>   col1       col2   col3
#>   <date>     <chr> <dbl>
#> 1 2020-01-01 A         8
#> 2 2020-01-01 B         3
#> 3 2020-02-01 A         2
#> 4 2020-02-01 B         9

I found several stackoverflow questions with this ggplot error, "Must request at least one colour from a hue palette.", but none of them had a solution. Mainly because the questions didn't include reproducible examples.

I've included a ReprEx (above and below). Why am I getting this error and how do I correct it?

ggplot(df, aes(col1, col3, fill = factor(col2, levels = rev(levels(col2))))) + 
  geom_col(position = "dodge", color = "black") 
#> Error: Must request at least one colour from a hue palette.
Display name
  • 4,153
  • 5
  • 27
  • 75
  • 3
    `factor(col2, levels = rev(levels(col2)))` is a vector of `NA` as col2 has no levels. Use `factor(col2, levels = rev(unique(col2)))` – stefan Jun 24 '20 at 12:48

1 Answers1

2

col2 is not a factor, so levels(col2) returns NA.

But, in fact you even don't need to deal with factors and reordering.

If you want the reverse order of bars, you can use position = position_dodge2(reverse = TRUE).

And if you want reverse order of the legend, you can use guides(fill = guide_legend(reverse = TRUE)).

So for your case:

ggplot(df, aes(col1, col3, fill = col2)) + 
    geom_col(position = position_dodge2(reverse = TRUE), color = "black") +
    guides(fill = guide_legend(reverse = TRUE)) 

ggplot