Reputation: 176
I want to add 2 trend lines to the barplot that I currently have.
This is the dataset that I have
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"))
As seen from the graph, the barplots are separated into 2011 and 2012. I would want to show 2 trend lines (2011 and 2012) on this graph to show the trend across the weekdays for both years.
Upvotes: 1
Views: 2323
Reputation: 5204
If by trendline you mean just a line that shows the same data as the bars but is connected...
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))
Created on 2021-03-15 by the reprex package (v1.0.0)
Upvotes: 1