【发布时间】:2020-06-24 15:35:53
【问题描述】:
library(tidyverse)
df <- tibble(col1 = as.Date(c("2020-01-01", "2020-01-01", "2020-01-01",
"2020-02-01", "2020-02-01", "2020-02-01")),
col2 = factor(rep(c("A", "B", "C"), 2), levels = c("C", "A", "B")),
col3 = c(8, 3, 2, 9, 1, 5))
df
#> # A tibble: 6 x 3
#> col1 col2 col3
#> <date> <fct> <dbl>
#> 1 2020-01-01 A 8
#> 2 2020-01-01 B 3
#> 3 2020-01-01 C 2
#> 4 2020-02-01 A 9
#> 5 2020-02-01 B 1
#> 6 2020-02-01 C 5
levels(df$col2)
#> [1] "C" "A" "B"
我已经创建了数据框df 和col2,如上所示。我认为这种因素的顺序决定了 ggplot 图例条目的默认顺序,但事实并非如此,如下所示。
ggplot(df, aes(col1, col3, fill = col2)) +
geom_col(data = df %>% filter(col2 != "C"),
position = "dodge",
color = "black") +
geom_col(data = df %>% filter(col2 == "C"),
width = 15,
color = "black") +
guides(fill = guide_legend(title = "Legend"))
我将推测 col2 级别排序 (#> [1] "C" "A" "B") 在 ggplot 的图例排序中不受尊重,因为有多个我的代码中的几何图形。它是否正确?如何让图例条目按以下顺序出现?
- C
- 一个
- B
【问题讨论】: