En esta sección veremos a la función creada “graf_ts” la cual recibe como parámetros a:
El primer parametro “se” es la serie de tiempo que se va a graficar.
El parametro “freq” el cual nos indicara la frecuencia con la que se avanza en el tiempo y la cual puede tomar tres valores pre definidos. Lo cuales son “month” que son meses, “quarter” que son cada cuatro meses y “year” que es cada 12 meses o un año.
Por ultimo “grafica” es el tipo de grafico que desea el usuario ya sea “ggplot”, “plot” o “plotly”
graf_ts<-function(se,freq, grafica){
if(class(se)=="ts"){
if(freq=="month"){
a<-paste(start(se)[1],start(se)[2],1,sep="/") %>% ymd()
b<-paste(end(se)[1],end(se)[2],1,sep="/") %>% ymd()
f<-seq.Date(from=a,to=b,by=freq)
} else if(freq=="quarter"){
a<-paste(start(se)[1],start(se)[2],sep="/") %>% yq()
b<-paste(end(se)[1],end(se)[2],sep="/") %>% yq()
f<-seq.Date(from = a,to=b,by=freq)
}else if(freq=="year"){
a<-paste(start(se)[1],1,1,sep="/") %>% ymd()
b<-paste(end(se)[1],1,1,sep="/") %>% ymd()
f<-seq.Date(from=a,to=b,by=freq)
}
s<-data.frame(Fechas=f,Valor=as.numeric(as.vector(se)))
} else{
stop('class(s1) is not ts')
}
if(grafica=="ggplot"){
g1<-ggplot(s)+geom_line(aes(x=Fechas,y=Valor), color="red", size=1.3)+
geom_point(aes(x=Fechas,y=Valor), color="blue", size=2)+ggtitle("Serie de tiempo")+
labs(x="Tiempo", y="Serie")+
theme_bw()+theme(plot.title = element_text(hjust = 0.5))
return(g1)
}else if(grafica=="plot"){
p1<-plot(x=s[,1],y=s[,2], col="red", main="Serie de tiempo", xlab = "Tiempo", ylab = "Serie",
lwd=1.5,pch=19)
lines(x=s[,1],y=s[,2], col="slateblue4", lwd=1.4)
return(p1)
}else if(grafica=="plotly"){
g1<-ggplot(s)+geom_line(aes(x=Fechas,y=Valor), color="black", size=1.3)+
geom_point(aes(x=Fechas,y=Valor), color="blue", size=2)+ggtitle("Serie de tiempo")+
labs(x="Tiempo", y="Serie")+
theme_bw()+theme(plot.title = element_text(hjust = 0.5))
return(ggplotly(g1))
}else{
stop('This option is not available')
}
}En esta parte se mostrarán tres ejemplos con 3 series de tiempos distintas y con distintos tipos de graficas citados en la anterior sección.
## NULL