Skip to main content
 首页 » 编程设计

python之Wireframe在numpy matplotlib mplot3d中加入错误方式

2024年10月24日7myhome

我正在尝试使用 matplotlib 在 Python 中创建 3D 线框。

然而,当我开始绘制实际的图表时,线框连接方式错误,如下图所示。

如何强制 matplotlib 沿某个轴连接线框?

我的代码如下:

import numpy as np 
import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import axes3d 
 
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 = 32*np.pi 
h = 0.01 
steps = int((t_f-t_0)/h) 
 
#3dify 
c_list = np.linspace(5,10,6) 
c_size = len(c_list) 
c_array = np.zeros((c_size,steps)) 
 
for i in range (0, c_size): 
    for j in range (0, steps): 
        c_array[i][j] = c_list[i] 
 
#create plotting values 
t = np.zeros((c_size,steps)) 
for i in range (0, c_size): 
    t[i] = np.linspace(t_0,t_f,steps) 
x = np.zeros((c_size,steps)) 
y = np.zeros((c_size,steps)) 
z = np.zeros((c_size,steps)) 
binvar, array_size = x.shape 
 
#initial conditions 
x[0] = 0 
y[0] = 0 
z[0] = 0 
 
for j in range(0, c_size-1): 
    for i in range(array_size-1): 
        c = c_list[j] 
        #re-evaluate the values of the x-arrays depending on the initial conditions 
        [x[j][i+1],y[j][i+1],z[j][i+1]]=rossler(x[j][i],y[j][i],z[j][i],t[j][i+1]-t[j][i],a,b,c) 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
ax.plot_wireframe(t,x,c_array, rstride=10, cstride=10) 
plt.show() 

我得到这个作为输出:

换个角度同样的输出:

而我希望线框沿着波峰连接。抱歉,我不能给你一张我想看的图片,这是我的问题,但我想它更像是教程图片。

请您参考如下方法:

如果我理解,您想将 6 条轨迹与多边形联系起来。您可以通过 2 乘 2 对迹线进行三角测量,然后绘制没有边缘或抗锯齿的表面来做到这一点。也许选择一个好的颜色图也会有所帮助。

请记住,这将是一个非常沉重的情节。导出的 SVG 重量为 10mb :)

import matplotlib.tri as mtri 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
for LineIndex in range(c_size-1): 
    # If plotting all at once, you get a MemoryError. I'll plot each 6 points 
    for Sample in range(0, array_size-1, 3): 
        # I switched x and c_array, because the surface  and the triangles  
        # will look better by default 
        X = np.concatenate([t[LineIndex,Sample:Sample+3], t[LineIndex+1,Sample:Sample+3]]) 
        Y = np.concatenate([c_array[LineIndex,Sample:Sample+3], c_array[LineIndex+1,Sample:Sample+3]]) 
        Z = np.concatenate([x[LineIndex,Sample:Sample+3], x[LineIndex+1,Sample:Sample+3]]) 
        T = mtri.Triangulation(X, Y) 
 
        ax.plot_trisurf(X, Y, Z, triangles=T.triangles, edgecolor='none', antialiased=False) 
 
ax.set_xlabel('t') 
ax.set_zlabel('x') 
plt.savefig('Test.png', format='png', dpi=600) 
plt.show() 

这是生成的图像: