1

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!

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

4 Comments

Waiting for the 10min timer to go :)
You should avoid the for loop altogether, just use data_cube = np.random.rand(10, 100, 100)
Ah true good point, this was just for demonstration purposes, my actual data is pre-determined but of the same shape.
@user3483203: Thanks for the wonderful suggestion. I am putting your suggestion in my answer with proper acknowledgement if it's fine with you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.