2017-11-11 117 views
1

我有一个问题,显示图中的数据。图框会出现,但不会显示图形。你能帮忙吗?蟒蛇3空图

我确信x轴的尺寸和数据是一样的......我根本找不到为什么我没有得到一个图形作为回报。

非常感谢您提前。

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.stats import norm 


n = 1000 
theta = 0.8 

d = np.sqrt(1-theta**2) 

def p(x,y): 
    "Stochastic kernel for the TAR model" 
    return norm().pdf((y-theta*np.abs(x))/d)/d 


Z = norm().rvs(n) 
X = np.empty(n) 

for t in range(n-1): 
    X[t+1] = theta*np.abs(X[t])+d*Z[t+1] 


n = len(X) 
X = X.reshape((n, 1)) 

ys = np.linspace(-3,3,200) 
k = len(ys) 
ys = ys.reshape((1,k)) 

v = p(X,ys) 
kernel = np.mean(v, axis=0)  
h = len(kernel) 
kernel = kernel.reshape((1,h)) 


fig, ax = plt.subplots(figsize=(10,7)) 
ax.plot(ys,kernel, 'b-', lw=2,alpha=0.6, label='look ahead estimate') 
plt.show() 

回答

0

的问题是,通过分别重塑两个1维阵列yskernel到1X k或1x h阵列你得到2维数组,其中第一维是1. plot功能显然只会遍历第一个维度,这就是为什么情节不显示任何内容。 我能想到的两种简单的方式来解决这个问题:

  1. 不要重塑变量kernelys

    # ... continuing your code ... 
    ys = np.linspace(-3,3,200) 
    k = len(ys) 
    #ys = ys.reshape((1,k)) 
    
    v = p(X,ys) 
    kernel = np.mean(v, axis=0)  
    h = len(kernel) 
    #kernel = kernel.reshape((1,h)) 
    
    
    fig, ax = plt.subplots(figsize=(10,7)) 
    ax.plot(ys,kernel, 'b-', lw=2,alpha=0.6, label='look ahead estimate') 
    plt.show() 
    
  2. 打电话给你的绘图功能是这样的:

    ax.plot(ys[0],kernel[0], 'b-', lw=2, alpha=0.6, label='look ahead estimate') 
    

我希望这可以解决您的问题。

要理解为什么你还是要重塑X:

让我们先了解你的函数p(x,y)在尺寸方面:

def p(x,y): 
    "Stochastic kernel for the TAR model" 
    """If x is not reshaped, you substract two one-dimensional arrays from each other, 
    which have not the same dimensions (dim(x) == 1000, dim(y) == 200 in your case). 
    This throws an error. 
    If you reshape X before passing to this function, the y array is substracted 
    element-wise by each of the values of X, which gives you a matrix with dimension 
    dim(x) x dim(y). 
    """ 
    return norm().pdf((y-theta*np.abs(x))/d)/d 

为了说明这里发生的事情逐个维度的:

>>> X = np.array([[1], [2], [3], [4]]) 
>>> Y = np.array([1, 2, 3]) 
>>> Y-X 
array([[ 0, 1, 2], 
     [-1, 0, 1], 
     [-2, -1, 0], 
     [-3, -2, -1]]) 

现在我们来看看返回的矩阵会发生什么:

kernelnp.mean(v, axis=0),其中v是从p(X,ys)返回的矩阵的计算,作品这样,即np.mean遍历所述矩阵v的线和在矩阵计算每一“行向量”的平均值。这给你一个一维数组(尺寸ys),你可以在ys上绘制。

+0

非常感谢你......现在正在工作。我做了你的建议,不是重塑内核和ys。我实际上很难理解为什么我仍然需要重塑X才能使其运行。你知道吗 ? – terman

+0

我想我终于明白了代码中会发生什么,并对答案进行了编辑,以便我能够解释它(希望)比评论中更容易理解。我希望现在很清楚为什么你必须重塑X而不是Y和核心:) – jmartin