Question

I want to plot bivariate correlation over time steps so that the x axis is the time and y axis is the bivariate correlation coefficient. The airquality data can be a good example for this. In this case I want to plot the correlation between Ozone&Temp and Ozone&Wind over Day. Thanks!

data(airquality)

The correlation matrix looks like this:

            Ozone Solar.R  Wind  Temp Month   Day
Ozone    1.00    0.35 -0.60  0.70  0.16 -0.01
Solar.R  0.35    1.00 -0.06  0.28 -0.08 -0.15
Wind    -0.60   -0.06  1.00 -0.46 -0.18  0.03
Temp     0.70    0.28 -0.46  1.00  0.42 -0.13
Month    0.16   -0.08 -0.18  0.42  1.00 -0.01
Day     -0.01   -0.15  0.03 -0.13 -0.01  1.00
Was it helpful?

Solution

With only one observation per day, it is not possible to compute a correlation. But you can compute the correlations on a moving window, e.g., with rollapply.

# Convert the data to time series
library(zoo)
d <- zoo( 
  airquality, 
  sprintf( "%02i-%02i", airquality$Month, airquality$Day ) 
)

# Compute the correlations
r <- rollapply( 
  d, 
  width = 7, 
  FUN = function(u) c( 
    cor(u[,"Ozone"], u[,"Temp"], use="pairwise"), 
    cor(u[,"Ozone"], u[,"Wind"], use="pairwise") 
  ), 
  by.column = FALSE,
  align = "right"
)

# Plot
matplot( 1:nrow(r), r, type="l", lwd=3, lty=1, axes=FALSE )
axis(2, las=1)
axis(1, at=1:nrow(r), labels=index(r), las=2)
box()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top