在python中使用matplotlib绘制轨迹

问题描述:

我在使用matplotlib绘制某些东西的路径时遇到了一些麻烦。 这是我正在做的事情的基本版本。在python中使用matplotlib绘制轨迹

本质上,我看到该值是否在路径中的任何点打破了某个阈值(在这种情况下为6),然后再对它进行处理。

现在,我有3个列表设置。 end_vector将基于其他两个列表。如果在单次模拟期间任何时候数值突破2,我会将对象的最后一个位置添加到我的end_vector

trajectories_vect是我想跟踪所有5个模拟的轨迹,保留一个列表名单。我会在下面澄清。并且,timestep_vect存储单个模拟的路径。

from random import gauss 
from matplotlib import pyplot as plt 
import numpy as np 

starting_val = 5 
T = 1     #1 year 
delta_t = .1   #time-step 
N = int(T/delta_t)  #how many points on the path looked at 
trials = 5    #number of simulations 

#main iterative loop 
end_vect = [] 
trajectories_vect = [] 
for k in xrange(trials): 
    s_j = starting_val 
    timestep_vect = [] 
    for j in xrange(N-1): 
     xi = gauss(0,1.0) 
     s_j *= xi 
     timestep_vect.append(s_j) 
    trajectories_vect.append(timestep_vect) 
    if max(timestep_vect) > 5: 
     end_vect.append(timestep_vect[-1]) 
    else: 
     end_vect.append(0) 

好了,此时如果打印我的轨迹,我得到这样的这一部分(我只发布了两个模拟,而不是完整的5):

[[ -3.61689976e+00 2.85839230e+00 -1.59673115e+00 6.22743522e-01 
1.95127718e-02 -1.72827152e-02 1.79295788e-02 4.26807446e-02 
-4.06175288e-02] [ 4.29119818e-01 4.50321728e-01 -7.62901016e-01 
-8.31124346e-02 -6.40330554e-03 1.28172906e-02 -1.91664737e-02 
-8.29173982e-03 4.03917926e-03]] 

这是好,什么我想要发生。

现在,我的问题是,我不知道如何正确绘制我的路径(y轴)与我的时间(x轴)。

首先,我想把我的数据放到numpy数组中,因为我稍后需要使用它们来计算一些统计数据和其他来自numpy的经验。

#creating numpy arrays from list 
#might need to use this with matplotlib somehow 
np_trajectories = np.array(trajectories_vect) 
time_array = np.arange(1,10) 

虽然这是问题的症结所在。当我将轨迹(y轴)放入matplotlib中时,它不会将每个“列表”(row in numpy)视为一条路径。 5次模拟没有获得5次路径,而是5次模拟得到9次路径。我相信我输入的东西是错误的,因此它以错误的方式使用了9个时间间隔。

#matplotlib stuff 
plt.plot(np_trajectories) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

这里的图像制作:

enter image description here

显然,这是错误的,前面提到的原因。相反,我想在我的轨迹中有5个基于5个列表(行)的路径。我似乎明白问题所在,但不知道如何解决问题。

在此先感谢您的帮助。

当您拨打np_trajectories = np.array(trajectories_vect)时,轨迹列表将转换为2d numpy阵列。有关其尺寸的信息存储在np_trajectories.shape中,在您的情况下,它是(5, 9)。因此,当您通过np_trajectoriesplt.plot()时,绘图库假定y值存储在第一维中,而第二维描述要绘制的各条线。

就你而言,你所要做的就是转置np_trajectories阵列。在numpy,它很简单,只要

plt.plot(np_trajectories.T) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

如果你要绘制的x轴的时间,而不是一个步骤中,您必须确定您的时间进程列表或数组。在numpy,你可以这样做

times = np.linspace(0, T, N-1) 
plt.plot(times, np_trajectories.T) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

产生如下图所示: timesteps

+0

真棒,即做到了。非常感谢。 只需快速跟进。我如何确保我的x轴与我的时间步保持一致?我希望它能反映delta_t;即具有时间段1-9。而现在,这不是那么做。 – DudeWah

+0

@DudeWah我已经更新了答案,其中包括将x轴绘制为时间序列(我认为是)您的情况。 –

+0

非常感谢您澄清一切! – DudeWah