Using R, I have a several time series and they have different time indices, like
date.a<-seq(as.Date('2014-01-01'),as.Date('2014-02-01'),by = 2)
date.b<-seq(as.Date('2014-01-01'),as.Date('2014-02-15'),by = 3)
df.a <- data.frame(time=date.a, A=sin((1:16)*pi/8))
df.b <- data.frame(time=date.b, B=cos((1:16)*pi/8))
I merge them into one xts
time series using
my.ts <- merge(xts(df.a$A,df.a$time),xts(df.b$B,df.b$time))
I want to display them both, either on separate panels, or in different colors in one.
Update:
Using xtsExtra
, I was able to display both series in one plot or each in a separate panel, using the following commands:
#one panel, different colors
plot(my.ts, screens=1, type="p")
#two panels, same color
plot(my.ts, screens=c(1,2), type="p")
This approach only works with type="p"
- plotting lines will not show the whole series, and create discontinuities. This is probably caused by the NA
s which were caused by merging the series. Which options do I have to work with these NA
s? I've found some, but I am not confident they are the best way.
na.omit(my.ts)
and na.exclude(my.ts)
seem to be too greedy - they only keep rows where both columns are not NA
. How do I chance this behavior to only a rowwise operation? na.approx(my.ts)
fills up the NA
s, but I am wondering if this linear approximation is creating artificial data points which would make the plot look differently. NA
s. Is there such a thing? Use na.approx
. Also note that zoo, which is already loaded by xts, is used here:
z <- na.approx(as.zoo(my.ts))
# plot.zoo
plot(z, screen = 1, col = 1:2, ylab = "Y", xlab = "")
# xyplot.zoo
library(lattice)
xyplot(z, screen = 1, col = 1:2, ylab = "Y", xlab = "")
# autoplot.zoo
library(ggplot2)
autoplot(z, facet = NULL) + ylab("Y")
Maybe you should do it without xts
(dont see the need for it) With ggplot2
a Solution might be
require(ggplot2)
ggplot()+geom_line(aes(x=time,y=A),data=df.a, col=2)+
geom_line(aes(x=time,y=B),data=df.b,col=3) + ylab("")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.