1

My data is like this

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

The date is my independent variable and Speed is my Dependent variable.

I'm trying to plot the trend line with a regression equation to understand if there is an increasing trend or decreasing trend.

I try to use this code but it did not show the equation in the graph.

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'

Example output that I want (the Correlation Equation and the Regression Equation) Sample Output

FrahChan04
  • 178
  • 1
  • 11
  • Maybe this question could give you some way to work it. Generally you just need geom_text in the right place with the formula – Sinh Nguyen May 05 '21 at 03:52
  • Perhaps my answer to a similar query [here](https://stackoverflow.com/questions/66977884/i-am-trying-to-create-an-exponent-instead-of-r2/66978474#66978474) will prove helpful. You can play around with the text annotations and see how you can get the positioning where you want it. I find it's usually a trial-and-error approach. – Speleo4Life May 05 '21 at 03:58
  • I was thinking the problem could be with the Date format. I have tried to play around with the location but it doesn't work. – FrahChan04 May 05 '21 at 04:17

1 Answers1

1

Here's the method I usually use:

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)

example_1.png

EDIT

With the p-value:

  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)

example_2.png

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46