r - 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.
解决方案
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))
推荐阅读
- git - Visual Studio Code、Windows、Git 客户端(版本 2.20.1)无法将代码推送到 GitHub 503 错误
- php - Send Push notification with Flutter + OneSignal for PlayerID
- ruby-on-rails - collect_select,我只想在下拉菜单中选择管理员角色为 true 的用户
- arrays - 推送函数似乎正在覆盖 Angular 中的每个数组元素
- c# - ASP.NET 用户不会出现在 SSMS 中
- java - 无法使用 SAX 解析器捕获元素
- linux - 双引号bash脚本linux
- python-3.x - 如何将多个单元格添加到bigtable表格中的一行?
- regex - 在 Notepad++ 中使用正则表达式在第二个冒号后擦除
- ssas - SSAS Cubes 在本地机器上处理,但不在服务器上