Python for循环在3D时总是绘制相同的线(使用matplotlib)

时间:2016-04-01 12:56:05

标签: python for-loop matplotlib plot mplot3d

我在Python中使用matplotlib在同一个图上绘制多条线,方法是使用for循环将每条线添加到轴上。

当以2D形式绘制时,每条线都在另一条线之上,这样可以正常工作。

然而,当在3D中绘图时,每次运行for循环时,python都会显示相同的图形数据,即使数据明显不同。

编辑:我不相信这个问题与“How can I tell if NumPy creates a view or a copy?”重复,因为它突出了一个特殊的意外行为实例。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

###### Unimportant maths not relevant to the question ######

def rossler(x_n, y_n, z_n, h, a, b, c):
    #defining the rossler function
    x_n1=x_n+h*(-y_n-z_n)
    y_n1=y_n+h*(x_n+a*y_n)
    z_n1=z_n+h*(b+z_n*(x_n-c))   
    return x_n1,y_n1,z_n1

#defining a, b, and c
a = 1.0/5.0
b = 1.0/5.0
c = 5

#defining time limits and steps
t_0 = 0
t_f = 50*np.pi
h = 0.01
steps = int((t_f-t_0)/h)

#create plotting values
t = np.linspace(t_0,t_f,steps)
x = np.zeros(steps)
y = np.zeros(steps)
z = np.zeros(steps)

##### Relevant to the question again #####

init_condition_array = [[0,0,0],[0.1,0,0],[0.2,0,0],[0.3,0,0]]
color_array = ["red","orange","green","blue"]
color_counter = 0
zs_array = [0, 0.1, 0.2, 0.3]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for row in init_condition_array:
    x[0] = row[0]
    y[0] = row[1]
    z[0] = row[2]

    for i in range(x.size-1):
        #re-evaluate the values of the x-arrays depending on the initial conditions
        [x[i+1],y[i+1],z[i+1]]=rossler(x[i],y[i],z[i],t[i+1]-t[i],a,b,c)

    plt.plot(t,x,zs=zs_array[color_counter],zdir="z",color=color_array[color_counter])
    color_counter += 1

ax.set_xlabel('t')
ax.set_ylabel('x(t)')
plt.show()  

正如您所看到的,图表应该看起来非常不同;

这是同一轴上的图形的二维图像,对代码进行了一些改动(如下所示):

虽然这是3D图表生成的图表:

2D图是通过对代码进行这些小改动而创建的;第一行上方的任何内容都没有改变:

init_condition_array = [[0,0,0],[0.1,0,0],[0.2,0,0],[0.3,0,0]]
color_array = ["red","orange","green","blue"]
color_counter = 0

fig = plt.figure()
ax = fig.add_subplot(111)

for row in init_condition_array:
    x[0] = row[0]
    y[0] = row[1]
    z[0] = row[2]

    for i in range(x.size-1):
        #re-evaluate the values of the x-arrays depending on the initial conditions
        [x[i+1],y[i+1],z[i+1]]=rossler(x[i],y[i],z[i],t[i+1]-t[i],a,b,c)

    plt.plot(t,x,color=color_array[color_counter],lw=1)
    color_counter += 1

ax.set_xlabel('t')
ax.set_ylabel('x(t)')
plt.show()  

1 个答案:

答案 0 :(得分:1)

x = np.zeros(steps)循环内部移动for row in init_condition_array修复/避免了问题。 x存储在Line3D返回的plt.plot个对象中,变异x会影响另一个Line3Ds中存储的值。

enter image description here

如果你追踪source code for Line3D,你会发现 传递给plt.plot的数据最终会导致Line3D _verts3d 属性。数据不会被复制; _verts3d元组保存对引用的引用 完全相同的数组。

以后在呈现时直接访问此_verts3d属性:

def draw(self, renderer):
    xs3d, ys3d, zs3d = self._verts3d

因此,即使在调用plt.plot之后,也会改变数据 - 变异self._verts3d。 这个简单的例子说明了这个问题:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
t = np.linspace(0, 1, 5)
x = np.sin(t)
line, = plt.plot(t, x, 0)

此处我们有x的原始值:

print(line._verts3d[1])
# [ 0.          0.24740396  0.47942554  0.68163876  0.84147098]

这表明变异x会修改line._verts3d

x[:] = 1
print(line._verts3d[1])
# [ 1.  1.  1.  1.  1.]

# The result is a straight line, not a sine wave.
plt.show()

制作2D线图时不会发生这种令人惊讶的陷阱,因为Line2D._xy属性保存用于渲染的数据存储原始数据的副本。

通过更改art3d.Line3D.set_3d_properties中的this line,可以在源代码中解决此问题

self._verts3d = art3d.juggle_axes(xs, ys, zs, zdir)

import copy
self._verts3d = copy.deepcopy(art3d.juggle_axes(xs, ys, zs, zdir))