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.
答案 0 :(得分:1)
col2
不是一个因素,所以levels(col2)
返回NA
。
但是,实际上,您甚至不需要处理因素和重新排序。
如果您希望条形反转,可以使用position = position_dodge2(reverse = TRUE)
。
如果您想颠倒图例的顺序,则可以使用guides(fill = guide_legend(reverse = TRUE))
。
对于您的情况:
ggplot(df, aes(col1, col3, fill = col2)) +
geom_col(position = position_dodge2(reverse = TRUE), color = "black") +
guides(fill = guide_legend(reverse = TRUE))