使用stat_smooth时按组设置线型

问题描述 投票:0回答:1

我有两个组的时间序列。我使用

stat_smooth
在时间序列图上显示两组的线性关系。我希望一组的最佳拟合线为实线,另一组的最佳拟合线为虚线。我可以接近我想要的,请参见下文,但我的尝试要么 1) 将线类型分配给错误的组,要么 2) 创建两个我想避免的图例。使用
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'

创建于 2024-05-15,使用 reprex v2.1.0

r ggplot2
1个回答
0
投票

基于@JonSpring 评论的答案。

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)
)

# From Figure 2

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') +
  scale_linetype_manual(values = c("z" = "solid", "a" = "dashed"), guide = "none") +
  theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'


# From Figure 3

df %>%
  ggplot(aes(x = date, y = value, group = group, linetype = fct_rev(group))) + 
  geom_line(aes(col = group), linetype = 'solid') +
  geom_point(aes(col = group), shape = 16) +
  stat_smooth(method = 'lm', se = F, color = 'black') +
  scale_linetype(guide = 'none') +
  theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'

创建于 2024-05-15,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.