ggplot 中的箱线图用于同一数据框中的两组数据

boxplot in ggplot for two groups of data in the same data frame

我想在 ggplot 中为同一数据框中的两组数据制作一个箱线图。一个适用于低于某个数字的所有年份,另一个适用于高于某个数字的所有年份。我试过子设置数据、带过滤器的管道和分组依据,但没有任何效果,我是 R 的新手。我觉得应该有一个简单的答案。我的数据框有三列:ID、Year 和 Amount。

我们可以用比较运算符创建一个组

library(dplyr)
library(ggplot2)
df1 %>%
   mutate(year_grp = case_when(year < 1969 ~ "below 1969", TRUE ~ ">= 1969")) %>%
   ggplot(aes(x = year_grp, y = anflow)) + 
     geom_boxplot()

-输出

数据

df1 <- structure(list(X = 1:31, year = 1950:1980, anflow = c(4910L, 
3660L, 3910L, 1750L, 1050L, 2670L, 2880L, 2600L, 3520L, 1730L, 
2340L, 2600L, 3410L, 1870L, 1730L, 2730L, 1550L, 4060L, 2870L, 
1350L, 2350L, 3140L, 3060L, 3630L, 3890L, 3870L, 3180L, 2260L, 
3430L, 5290L, 2870L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", 
"25", "26", "27", "28", "29", "30", "31"))