rh1990
rh1990

Reputation: 940

Plot 3rd axis of a 3D numpy array

I have a 3D numpy array that is a stack of 2D (m,n) images at certain timestamps, t. So my array is of shape (t, m, n). I want to plot the value of one of the pixels as a function of time.

e.g.:

import numpy as np
import matplotlib.pyplot as plt

data_cube = []
for i in xrange(10):
    a = np.random(100,100)
    data_cube.append(a)

So my (t, m, n) now has shape (10,100,100). Say I wanted a 1D plot the value of index [12][12] at each of the 10 steps I would do:

plt.plot(data_cube[:][12][12])
plt.show()

But I'm getting index out of range errors. I thought I might have my indices mixed up, but every plot I generate seems to be in the 'wrong' axis, i.e. across one of the 2D arrays, but instead I want it 'through' the vertical stack. Thanks in advance!

Upvotes: 1

Views: 535

Answers (1)

Sheldore
Sheldore

Reputation: 39042

Here is the solution: Since you are already using numpy, convert you final list to an array and just use slicing. The problem in your case was two-fold:

First: Your final data_cube was not an array. For a list, you will have to iterate over the values

Second: Slicing was incorrect.

import numpy as np
import matplotlib.pyplot as plt

data_cube = []
for i in range(10):
    a = np.random.rand(100,100)
    data_cube.append(a)
data_cube = np.array(data_cube)   # Added this step 

plt.plot(data_cube[:,12,12]) # Modified the slicing

Output

enter image description here

A less verbose version that avoids iteration:

data_cube = np.random.rand(10, 100,100)
plt.plot(data_cube[:,12,12])

Upvotes: 2

Related Questions