Plot only one or few rows of a correlation matrix

1.8k views Asked by At

I have a correlation matrix named corrdata that I calculated using numpy.corrcoef. Then what I do is extract one or a few rows of this matrix, and now just want to plot them instead of the whole matrix. Because the matrix is no longer square, it is not possible to plot the data using pcolor, imshow, or the likes.

So I want to ask for the best alternative way to plot these extracted correlation coefficients and get the same appearance as the correlation matrix would in terms of coloured squares representing the value of the correlation coefficient, but only showing a few rows of the full matrix.

1

There are 1 answers

3
ali_m On BEST ANSWER

You can simply insert an extra singleton dimension in order to turn your (n,) 1D vector into a (1, n) 2D array, then use pcolor, imshow etc. as normal:

import numpy as np
from matplotlib import pyplot as plt

# dummy correlation coefficients
coeffs = np.random.randn(10, 10)
row = coeffs[0]

# indexing with None (or equivalently, np.newaxis) inserts an extra singleton
# dimension
plt.imshow(row[None, :], cmap=plt.cm.jet, interpolation='nearest')

enter image description here

See here for some more ways to convert a 1D vector to a 2D array.