【问题标题】:How to plot trend line with regression equation in R?如何用R中的回归方程绘制趋势线?
【发布时间】:2021-05-05 03:42:53
【问题描述】:

我的数据是这样的

Date Speed
1/2019 4500
2/2019 3400
3/2019 5300
4/2019 2000

日期是我的自变量,速度是我的因变量。

我正在尝试使用回归方程绘制趋势线,以了解是否存在上升趋势或下降趋势。

我尝试使用此代码,但它没有在图表中显示方程式。

ggscatter(a, x = "Date", y = "Speed", add = "reg.line") +
stat_cor(label.x = 03/2019, label.y = 3700) +
stat_regline_equation(label.x = 03/2019, label.y = 3600)
#> `geom_smooth()` using formula 'y ~ x'

我想要的示例输出(相关方程和回归方程)

【问题讨论】:

  • 也许这个问题可以给你一些解决方法。通常,您只需要使用公式将 geom_text 放在正确的位置
  • 也许我对类似查询here 的回答会有所帮助。您可以使用文本注释并查看如何获得所需的位置。我发现这通常是一种试错法。
  • 我认为问题可能出在日期格式上。我尝试过使用该位置,但它不起作用。

标签: r


【解决方案1】:

这是我常用的方法:

library(tidyverse)
library(lubridate)
library(ggpmisc)

df <- tibble::tribble(
     ~Date, ~Speed,
  "1/2019",  4500L,
  "2/2019",  3400L,
  "3/2019",  5300L,
  "4/2019",  2000L
  )
df$Date <- lubridate::my(df$Date)

ggplot(df, aes(x = Date, y = Speed)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE) +
  stat_poly_eq(formula = x ~ y, 
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
               parse = TRUE)

编辑

用p值:

  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE) +
  stat_poly_eq(formula = x ~ y, 
               aes(label = paste(..eq.label.., ..rr.label.., ..p.value.label.., sep = "~~~")), 
               parse = TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2020-11-28
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多