2

I'm having a problem trying to plot a series of lines in a 3D plot in MatPlotLib. When I run the code below all the lines are plotted at the last value of y??? Even though y is correctly incremented in the loop. Any Help understanding this would be appreciated. Thanks David

#========== Code Start=================
import numpy as np
import matplotlib
from matplotlib.figure import Figure
import pylab as plt
from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = Axes3D(fig)
x=np.arange(5)
y=np.zeros(len(x))

for i in range(1,10):
    y.fill(i)
    z=plt.randn(len(y))
    ax.plot(xs=x, ys=y, zs=z)#, zdir='z', label='ys=0, zdir=z')
    plt.draw()
    print i,len(y),y,x,z
plt.xlabel('X') 
plt.ylabel('Y')
plt.zlabel('Z')   
plt.show()
#========== Code End=================

1 Answer 1

1

It looks like y might be pointed to by all plots. So you are passing the reference to y when you execute ax.plot. It is the same reference each time, but the values are changed on each pass. When the plt.show() is executed the reference to y is used and it is now set at 9. So, create a different object for y on each pass with the values you want for that pass:

y = np.zeros(len(x))
y.file(i)

There might be a numpy command that fills with the value you want in one go, but you get the picture.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Demolishan, you are correct. Putting the y=np.zeros(len(x)) within the loop does retain the correct y index for the final plot. I didn't realize y had that persistance in the plot too.

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.