如何从数组中的数据在matplotlib中创建3D线图?

时间:2016-01-02 23:19:35

标签: python arrays matplotlib plot

我使用SciPy用脚本数字解决了Lorenz方程:

# Lorenz Equations SciPy solver
import numpy as np
from scipy import integrate
from math import cos
from matplotlib import pyplot as plt
a, b = 0, 100
sigma, rho, beta = 10, 28, 8/3
N = 1000000
h = (b-a) / float(N)

def solvr(Y, t):
    return [sigma*(Y[1]-Y[0]), Y[0]*(rho-Y[2])-Y[1], Y[0]*Y[1]-beta*Y[2]]

t    = np.arange(a, b, h)
asol = integrate.odeint(solvr, [0, 1, 1], t)
x    = asol[:,0]
y    = asol[:,1]
z    = asol[:,2]

现在我想做的是在3D线上相互对抗xyz(这些都是Numpy ndarrays,如果你不确定)线框)情节。我认为这必须使用matplotlib完成,但我并不挑剔,只要你给我一个能用3D绘制数据的解决方案我不关心我需要导入哪些模块。

2 个答案:

答案 0 :(得分:5)

以下是Lorenz吸引子的3D和动画。该剧本在Jake VanderPlas的以下链接中(以及许多好东西)' Pythonic Perambulations。您可以通过逐行浏览脚本来学到很多东西 - 它是对matplotlib个对象的优雅使用。

https://jakevdp.github.io/blog/2013/02/16/animating-the-lorentz-system-in-3d/

我在return函数中animate之前添加了这两行,然后使用ImageJ导入"图像堆栈"并保存"动画GIF":

fname = "Astro_Jake_" + str(i+10000)[1:]
fig.savefig(fname)

注意:对于OSX,似乎有必要在blit = False中设置animation.FuncAnimationAstro Jake

以下是基于以上内容绘制3D线条的最小简化示例:

def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):
    """Compute the time-derivative of a Lorentz system."""
    return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.integrate import odeint as ODEint

x = np.linspace(0, 20, 1000)
y, z = 10.*np.cos(x), 10.*np.sin(x) # something simple

fig = plt.figure()
ax = fig.add_subplot(1,2,1,projection='3d')
ax.plot(x, y, z)

# now Lorentz
times = np.linspace(0, 4, 1000) 

start_pts = 30. - 15.*np.random.random((20,3))  # 20 random xyz starting values

trajectories = []
for start_pt in start_pts:
    trajectory = ODEint(lorentz_deriv, start_pt, times)
    trajectories.append(trajectory)

ax = fig.add_subplot(1,2,2,projection='3d')
for trajectory in trajectories:
    x, y, z = trajectory.T  # transpose and unpack 
    # x, y, z = zip(*trajectory)  # this also works!
    ax.plot(x, y, z)

plt.show()

screen shot of simplified 3D Lorenz

答案 1 :(得分:3)

有关如何在matplotlib网站http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots上进行线框图(以及三维散点图)的简短示例/教程