Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine 2 matrices into a graph

Tags:

plot

r

matrix

I have 2 symmetric matrices (mathematical meaning of matrices), one with distances between locations (the locations are coded with 4 digit numbers:2030, 2059, 2095...) that looks like this:
2030 2059 2095 ...
2030 NA 59328 68464
2059 59328 NA 37196
2095 68464 37196 NA
...

and another with the correlations between locations :
2030 2059 2095...
2030 1.0000000 0.4651804 0.6185849
2059 0.4651804 1.0000000 0.4428746
2095 0.6185849 0.4428746 1.0000000
...

I need to combine these 2 matrices in a plot of correlations vs. distances but have no idea how to do it in R and considering I have more than 80 locations I don't want to do it manually! Does anyone know of a way to do it?

Thanks!

like image 948
sbg Avatar asked Jan 24 '26 22:01

sbg


2 Answers

If you just want to plot correlations as a function of distances, without imposing a particular structure on your plot, you can just extract the lower part of your respective matrices, e.g.

x <- matrix(rnorm(1000), nrow=20)
d.mat <- as.matrix(dist(x))
c.mat <- cor(t(x))
plot(d.mat[lower.tri(d.mat)], c.mat[lower.tri(c.mat)])
like image 69
chl Avatar answered Jan 26 '26 14:01

chl


Assuming your matrices are stored in m1 and m2, does this work:

dat <- data.frame(a=as.vector(m1[upper.tri(m1)]),
          b=as.vector(m2[upper.tri(m2)]))
plot(dat$a,dat$b)
like image 24
joran Avatar answered Jan 26 '26 14:01

joran