首页 > 解决方案 > ggplot - 错误:必须从色调调色板中请求至少一种颜色

问题描述

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

我发现了几个与此 ggplot 错误有关的 stackoverflow 问题,“必须从色调调色板中请求至少一种颜色。 ”,但没有一个有解决方案。主要是因为这些问题不包括可重复的例子。

我已经包括了一个ReprEx(上面和下面)。为什么我会收到此错误,我该如何纠正?

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.

标签: rggplot2

解决方案


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


推荐阅读