I have a time series for two groups. I am using stat_smooth
to display the linear relationship for the two groups on a time series plot. I want the line of best fit to be solid for one group and dashed for the other group. I can get close to what I want, please see below, but my attempts either 1) assigns the line type to the wrong group or 2) creates two legends which I want to avoid. How can I assign a specific line type to a specific group when using stat_smooth
?
library(tidyverse)
# Example time series
set.seed(222)
df <- data.frame(
date = rep(seq(as.Date('2024-04-01'),
as.Date('2024-04-05'),
'1 day'), times = 2),
group = c('a','a','a','a','a',
'z','z','z','z','z'),
value = rnorm(10, 1, 2)
)
# Figure 1 (both groups same line type)
df %>%
ggplot(aes(x = date, y = value, group = group)) +
geom_line(aes(col = group)) +
geom_point(aes(col = group), shape = 16) +
stat_smooth(method = 'lm', se = F, color = 'black') +
theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'
# Figure 2 (line type changed but assigned to wrong groups)
df %>%
ggplot(aes(x = date, y = value, group = group, linetype = group)) +
geom_line(aes(col = group), linetype = 'solid') +
geom_point(aes(col = group), shape = 16) +
stat_smooth(method = 'lm', se = F, color = 'black') +
theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'
# Figure 3 (line type assigned to correct groups but now a second legend appears)
df %>%
ggplot(aes(x = date, y = value, group = group, linetype = fct_rev(group))) + # NOTE same thing happend when using rev()
geom_line(aes(col = group), linetype = 'solid') +
geom_point(aes(col = group), shape = 16) +
stat_smooth(method = 'lm', se = F, color = 'black') +
theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'
Created on 2024-05-15 with reprex v2.1.0