Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created August 23, 2025 15:39
Show Gist options
  • Select an option

  • Save abikoushi/bfaa806d19b55640aa949830926b6c3f to your computer and use it in GitHub Desktop.

Select an option

Save abikoushi/bfaa806d19b55640aa949830926b6c3f to your computer and use it in GitHub Desktop.
Visualize QR algorithm for covariance matrix
library(mvtnorm)
library(reshape2)
library(ggplot2)
library(gganimate)
library(dplyr)
Sig = matrix(c(1,0.8,0.8,1),2,2)
scatters = vector("list", 5)
heats = vector("list", 5)
X = rmvnorm(5000, sigma=Sig)
df_sig = melt(Sig, varnames = c("row","column"))
scatters[[1]] = data.frame(X, it=1)
heats[[1]] = mutate(df_sig, it=1)
for(i in 2:5){
res_qr = qr(Sig)
Q = qr.Q(res_qr)
Sig = t(Q)%*%Sig%*%Q
X = rmvnorm(1000, sigma=Sig)
df_sig = melt(Sig, varnames = c("row","column"))
scatters[[i]] = data.frame(X, it=i)
heats[[i]] = mutate(df_sig, it=i)
}
scatters = bind_rows(scatters)
heats = bind_rows(heats)
p1 = ggplot(scatters,aes(X1,X2))+
geom_point(alpha=0.25)+
facet_wrap(~it)+
theme_bw(18)
print(p1)
p1 = ggplot(scatters,aes(X1,X2))+
geom_point(alpha=0.25)+
transition_manual(it)+
theme_bw(18)
print(p1)
p2 = ggplot(heats, aes(x=column, y=row, fill=value))+
geom_tile(colour="grey") +
facet_wrap(~it)+
scale_fill_gradient2()+
scale_x_continuous(breaks=1:2)+
scale_y_reverse(breaks=1:2)+
theme_bw(18)
print(p2)
p2 = ggplot(heats, aes(x=column, y=row, fill=value))+
geom_tile(colour="grey") +
transition_manual(it)+
scale_fill_gradient2()+
scale_x_continuous(breaks=1:2)+
scale_y_reverse(breaks=1:2)+
theme_bw(18)
print(p2)
anim_save(filename = "qr_rnorm.gif", animation = p1)
anim_save(filename = "qr_cov.gif", animation = p2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment