Python 3.x 如何在阵列中使用Aray进行绘图?

Python 3.x 如何在阵列中使用Aray进行绘图?,python-3.x,matplotlib,ode,Python 3.x,Matplotlib,Ode,我有一个耦合质量系统代码,运行良好并打印结果。但是我很难绘制位置和速度的图形,因为我无法从数组中提取值。我会很感激你的帮助 import numpy as np %matplotlib inline import matplotlib.pyplot as pl from scipy.integrate import odeint def vectorfield(w, t, p): x1, y1, x2, y2 = w m1, m2, k1, k2, kc = p

我有一个耦合质量系统代码,运行良好并打印结果。但是我很难绘制位置和速度的图形,因为我无法从数组中提取值。我会很感激你的帮助

import numpy as np
%matplotlib inline
import matplotlib.pyplot as pl

from scipy.integrate import odeint

def vectorfield(w, t, p):
    
    x1, y1, x2, y2 = w
    m1, m2, k1, k2, kc = p

    # Create f = (x1',y1',x2',y2'):
    f = [y1, (-x1*(k1+kc) + x2*kc)/m1, y2, (x1*kc - x2*(k2+kc)) / m2]
    return f


# Parameter values
# Masses:
m1 = 1.0
m2 = 1.0
# Spring constants
k1 = 4.0
k2 = 1.0
kc = 0.1

# Initial conditions
# x1 and x2 are the initial displacements; y1 and y2 are the initial velocities
x1 = -2.0
y1 = 5.0
x2 = 2.0
y2 = 10.0

# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
stoptime = 100.0
numpoints = 250
t = [stoptime * float(i) / (numpoints - 1) for i in range(numpoints)]

# Pack up the parameters and initial conditions:
p = [m1, m2, k1, k2, kc]
w0 = [x1, y1, x2, y2]

# Call the ODE solver.
wsol = odeint(vectorfield, w0, t, args=(p,), atol=abserr, rtol=relerr)


# Print solution
for t1, w1 in zip(t, wsol):
    AZ = [t1, w1[0], w1[1], w1[2], w1[3]]
    
    print(AZ)
我曾尝试在网上搜索,但并不是找不到一个合适的解决方案。我试过了

with open('coupled_masses.dat', 'w') as f:
    for t1, w1 in zip(t, wsol):
       print(f, t1, w1[0], w1[1], w1[2], w1[3])
import matplotlib.pyplot as plt;
from matplotlib.font_manager import FontProperties;
# get saved values from saved file
t, x1, y1, x2, y2 = np.loadtxt('coupled_masses.dat', unpack=True);

但是它不起作用

这就是你想要的吗?在此处使用列表理解,然后转换为numpy数组

from scipy.integrate import odeint

def vectorfield(w, t, p):
    
    x1, y1, x2, y2 = w
    m1, m2, k1, k2, kc = p

    # Create f = (x1',y1',x2',y2'):
    f = [y1, (-x1*(k1+kc) + x2*kc)/m1, y2, (x1*kc - x2*(k2+kc)) / m2]
    return f


# Parameter values
# Masses:
m1 = 1.0
m2 = 1.0
# Spring constants
k1 = 4.0
k2 = 1.0
kc = 0.1

# Initial conditions
# x1 and x2 are the initial displacements; y1 and y2 are the initial velocities
x1 = -2.0
y1 = 5.0
x2 = 2.0
y2 = 10.0

# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
stoptime = 100.0
numpoints = 250
t = [stoptime * float(i) / (numpoints - 1) for i in range(numpoints)]

# Pack up the parameters and initial conditions:
p = [m1, m2, k1, k2, kc]
w0 = [x1, y1, x2, y2]

# Call the ODE solver.
wsol = odeint(vectorfield, w0, t, args=(p,), atol=abserr, rtol=relerr)

# Print solution
data = np.array([[t1, w1[0], w1[1], w1[2], w1[3]] for t1, w1 in zip(t, wsol)])

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7.2, 7.2/2))
ax1.plot(data[:, 0], data[:, 1])
ax2.plot(data[:, 0], data[:, 3])

我想为w1[0]vs t1和w1[2]vs t1绘制两张图。请参阅更新的代码,如果它解决了您的问题,请接受。