【问题标题】:plotting linear time trend using facet使用 facet 绘制线性时间趋势
【发布时间】:2017-02-18 04:53:01
【问题描述】:

我想使用facet wrap 在数据点上叠加一个线性趋势回归模型:

我正在寻找的线性回归是

value ~ time 其中时间是seq(1:length(dates))

在下面的示例中,A 组有 3 个观察值,B 组有 4 个观察值

我的代码是

dates = as.Date(c("2017-01-01", "2017-02-01", "2017-03-01", "2017-01-01", "2017-02-01", 
    "2017-03-01", "2017-04-01"))
group = c("A", "A", "A", "B", "B", "B", "B")
value = c(2, 3, 1, 1, 3, 2, 5)
data = data.frame(dates = dates, group = group, value = value)


ggplot(data = data, aes(x = factor(dates), y = value, group = 1)) + 
    geom_point() + 
    geom_line() + 
    geom_smooth(method = "lm", formula = value ~ seq(1:length(dates))) + 
    facet_wrap(~group, ncol = 1, scales = "free_y")

我还想在图表上打印回归的斜率系数

有什么想法吗?

【问题讨论】:

  • formula 是在美学方面指定的,即xy。不过,在这种情况下,您可以摆脱它并使用geom_smooth(method = 'lm')。打印坡度需要更多的工作,因为它不是通过stat_smooth 提供的数量。首先进行建模、组装数据然后绘图可能更容易。

标签: r regression linear-regression


【解决方案1】:

通过一点点 tidyverse 魔法,您可以将模型保存在 data.frame 中,这样您就可以绘制任何您想要的东西:

library(tidyverse)

data %>% nest(-group) %>% 
    mutate(model = map(data, ~lm(value ~ dates, data = .x)), 
           predictions = map(model, predict), 
           slope = map_dbl(model, ~coef(.x)[2])) %>% 
    unnest(data, predictions) %>% 
    ggplot(aes(dates, value)) + 
    geom_line(color = 'gray50') + 
    geom_point() + 
    geom_line(aes(y = predictions), color = 'blue', size = .75) + 
    geom_text(aes(label = paste('beta==', round(slope, 5)), 
                  x = min(dates) + 1, 
                  y = max(value)), 
              hjust = 0, parse = TRUE) + 
    facet_wrap(~group, ncol = 1, scales = 'free_y')

如果您愿意,也可以手动绘制置信区间,或者像往常一样使用geom_smooth

data %>% nest(-group) %>% 
    mutate(model = map(data, ~lm(value ~ dates, data = .x)), 
           slope = map_dbl(model, ~coef(.x)[2])) %>% 
    unnest(data) %>% 
    ggplot(aes(dates, value)) + 
    geom_line(color = 'gray50') + 
    geom_point() + 
    geom_smooth(method = 'lm') +
    geom_text(aes(label = paste('beta==', round(slope, 5)), 
                  x = min(dates) + 1, 
                  y = max(value)), 
              hjust = 0, parse = TRUE) + 
    facet_wrap(~group, ncol = 1, scales = 'free_y')

请注意,这种方法的计算量更大,因为 geom_smooth 会重新调整模型。如果您愿意,扫帚和建模器也可以用于处理模型。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    data$id <- ave(data$value, data$group, FUN=seq_along)
    
    ggplot(data = data, aes(x = factor(dates), y = value, group = group)) + 
      geom_point() + 
      geom_line() + 
      geom_smooth(method = "lm", aes(x=id, y=value)) + 
      facet_wrap(~group, ncol = 1, scales = "free_y")
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2017-06-13
      • 2016-09-09
      • 2022-07-05
      • 2021-02-14
      • 1970-01-01
      相关资源
      最近更新 更多