Using ggplot and the following code I created the plot below:
df_have %>%
ggplot(aes(date, num_visits))
geom_line(colour = "blue")
ggtitle("Number of Customers Visiting Store by Month")
geom_smooth(method = "lm", fit = num_visits ~ date, se=F, color="red")
xlab("Date")
ylab("Number of Visits")
However, I am wondering how to:
add a legend differentiating between the blue line (number of visits) and red line (line of best fit) and
annotate this chart with the equation of the red line in the form of
y = mx c
Thanks!
Edit: Sample data
df_have
num_visits date
1 19.825 2021.000
2 25.025 2021.083
3 27.950 2021.167
4 25.425 2021.250
5 29.575 2021.333
CodePudding user response:
Update: One way could be using ggpmisc
package:
library(tidyverse)
library(ggpmisc)
my.formula <- y ~ x
df_have %>%
ggplot(aes(date, num_visits))
geom_line(aes(colour = "blue"))
ggtitle("Number of Customers Visiting Store by Month")
geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red"))
stat_poly_eq(formula = my.formula,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE)
xlab("Date")
ylab("Number of Visits")
scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx c'))
First_answer: You mean this kind of output?
df_have %>%
ggplot(aes(date, num_visits))
geom_line(aes(colour = "blue"))
ggtitle("Number of Customers Visiting Store by Month")
geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red"))
xlab("Date")
ylab("Number of Visits")
scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx c'))