我想向我目前拥有的条形图添加 2 条趋势线。
这是我拥有的数据集
structure(list(yr = c("2011", "2011", "2011", "2011", "2011",
"2011", "2011", "2012", "2012", "2012", "2012", "2012", "2012",
"2012"), weekday = structure(c(5L, 1L, 6L, 7L, 4L, 2L, 3L, 5L,
1L, 6L, 7L, 4L, 2L, 3L), .Label = c("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"), class = "factor"),
cnt = c(181975L, 181469L, 171142L, 169104L, 183436L, 188807L,
166547L, 295964L, 306332L, 291879L, 288597L, 290031L, 301096L,
275677L)), row.names = c(NA, -14L), groups = structure(list(
yr = c("2011", "2012"), .rows = structure(list(1:7, 8:14), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
从图中可以看出,条形图分为 2011 年和 2012 年。我想在此图上显示 2 条趋势线(2011 年和 2012 年),以显示这两年工作日的趋势。
答案 0 :(得分:1)
如果您所说的趋势线只是一条显示与条形图相同的数据但相互连接的线...
library(tidyverse)
data <- structure(list(yr = c("2011", "2011", "2011", "2011", "2011",
"2011", "2011", "2012", "2012", "2012", "2012", "2012", "2012",
"2012"), weekday = structure(c(5L, 1L, 6L, 7L, 4L, 2L, 3L, 5L,
1L, 6L, 7L, 4L, 2L, 3L), .Label = c("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"), class = "factor"),
cnt = c(181975L, 181469L, 171142L, 169104L, 183436L, 188807L,
166547L, 295964L, 306332L, 291879L, 288597L, 290031L, 301096L,
275677L)), row.names = c(NA, -14L), groups = structure(list(
yr = c("2011", "2012"), .rows = structure(list(1:7, 8:14), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
data %>%
ggplot(aes(x = weekday, y = cnt, group = yr)) +
geom_col(aes(fill = yr), position = position_dodge(width = 1)) +
geom_line(aes(color = yr), position = position_dodge(width = 1))
由 reprex package (v1.0.0) 于 2021 年 3 月 15 日创建