I have two datas in one column by their name in y axis, and a datetime in x axis.
I try to calculate numeric deriv for each two datas, but I don't understand derive in R. (I've looking for stats::D
or diff
but It doesn't work).
f(x)=(t_n-t_n-1)/(date_time_n / date_time_n -1)
where f(x) will be my calc column.
ie to replace my calc=t/10
, in the code below, by a function doing this. (I would prefer tidyverse / dplyr)
Links
- Calculate the derivative of a data-function in r
- My previous question To add a legend by shape in ggplot ( added 2nd question after: to calculate numeric deriv)
Below : ggplot picture of calc=t/10
where calc
will be replaced by the derive.
library(tidyverse)
library(ggplot2)
datas<-data.frame(
t = c(
50 + c(0, cumsum(runif(9, -7, 7))),
70 + c(0, cumsum(runif(9, -10, 10)))
),
orig=c(rep("s1",10),rep("s2",10)),
date_heure = rep(
seq(from=as.POSIXct("2012-1-1 0:00", tz="UTC"),by="hour", length=10) ,
2
)
)
datas<- (datas
%>% mutate (
calc=t/10
)
)
(
ggplot(datas)
+ geom_line(mapping=aes(x = date_heure, y = t, color=orig, linetype = "s1"))
+ geom_line(mapping=aes(x = date_heure, y = calc, color=orig, linetype = "s2"))
+ scale_y_continuous(name = "t", sec.axis = sec_axis(trans=~(range(datas$calc)), name = "calc"))
+ geom_point(mapping = aes(x = date_heure, y = calc, color=orig), shape = 21, fill = "white")
+ scale_color_manual(name = "calc", values=c("red", "blue"))
+ scale_linetype_manual(name = "orig", values = c('solid', 'solid'),
guide = guide_legend(override.aes = list(colour=c("red", "blue"))))
)