可以使用ggplot2中的group参数来实现按年份分组的效果。首先需要准备包含年份信息的数据集,例如包含year和value两列的数据集。在绘制geom_line时,将group参数设置为year即可实现按年份分组的效果,示例代码如下:
library(ggplot2)
# 准备数据
df <- data.frame(year = c(rep(2018, 3), rep(2019, 3), rep(2020, 3)),
value = c(1, 2, 3, 2, 1, 3, 3, 1, 2))
# 绘制图形
ggplot(df, aes(x = 1:3, y = value, group = year, color = as.factor(year))) +
geom_line() +
labs(x = NULL, y = "value", color = "year") +
theme_bw()
运行以上代码,即可得到按年份分组的折线图。其中,group参数设置为year,表示按year分组;color参数设置为as.factor(year),表示以不同年份的折线颜色区分。
上一篇:按年份分组的总和
下一篇:按年份分组数据并筛选所有年份。