newb
newb

Reputation: 37

graph the contents of a matrix in python (using matplotlib)

Hi I need to graph the contents of a matrix where each row represents a different feature and each column is a different time point. In other words, I want to see the change in features over time and I have stacked each feature in the form of a matrix. C is the matrix

A=C.tolist() #convert matrix to list.
R=[]
for i in xrange(len(A[0])):
    R+=[[i]*len(A[i])]    
for j in xrange(len(A[0])):
    S=[]
    S=C[0:len(C)][j]
    pylab.plot(R[j],S,'r*')
pylab.show()

Is this right/is there a more efficient way of doing this? Thanks!

Upvotes: 3

Views: 25737

Answers (2)

Avaris
Avaris

Reputation: 36715

From the docs:

matplotlib.pyplot.plot(*args, **kwargs):

[...]

plot(y)            # plot y using x as index array 0..N-1
plot(y, 'r+')      # ditto, but with red plusses

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

So if A has the values in columns, it is as simple as:

pylab.plot(A, 'r*')  # making all red might be confusing, '*-' might be better

If your data is in rows, then plot the transpose of it:

pylab.plot(A.T, 'r*')

Upvotes: 9

aaren
aaren

Reputation: 5675

You can extract column i of a matrix M with M[:,i] and the number of columns in M is given by M.shape[1].

import matplotlib.pyplot as plt

T = range(M.shape[0])

for i in range(M.shape[1]):
    plt.plot(T, M[:,i])

plt.show()

This assumes that the rows represent equally spaced timeslices.

Upvotes: 5

Related Questions