Python 如何将两个变量设置为相同的形状/格式以进行绘图?

Python 如何将两个变量设置为相同的形状/格式以进行绘图?,python,matplotlib,shapes,Python,Matplotlib,Shapes,当我试图绘制x和y时,Python说“ValueError:x和y必须具有相同的第一维度,但具有形状(2,)和(1,)”。 我能做什么? 徖 import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from scipy.optimize import fmin def blscall(S,K,T,r,sigma): d1 = 1/sigma/np.sqrt(T)*(np.log(S

当我试图绘制x和y时,Python说“ValueError:x和y必须具有相同的第一维度,但具有形状(2,)和(1,)”。 我能做什么?

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm 
from scipy.optimize import fmin 
def blscall(S,K,T,r,sigma):
    d1 = 1/sigma/np.sqrt(T)*(np.log(S/K) + (r+sigma**2/2)*T) 
    d2 = d1 - sigma*np.sqrt(T)
    return(S*norm.cdf(d1)-K*np.exp(-r*T)*norm.cdf(d2))
def blsput(S,K,T,r,sigma):
    d1 = 1/sigma/np.sqrt(T)*(np.log(S/K) + (r+sigma**2/2)*T) 
    d2 = d1 - sigma*np.sqrt(T)
    return(-S*norm.cdf(-d1)+K*np.exp(-r*T)*norm.cdf(-d2))
C = np.array([
[220.00, 28.00, 28.15, 28.35, 622 , 27.27    ],
[225.00, 23.70, 23.85, 24.00, 386 ,    26.26  ],
[230.00, 20.00, 19.65, 20.60, 492 ,    27.78  ],
[235.00, 16.10, 16.00, 16.10, 2180, 24.60  ],
[240.00, 12.62, 12.60, 12.75, 2353, 24.12  ],
[245.00, 9.65 ,   9.50, 9.70 ,  2870, 23.35  ],
[250.00, 7.05 ,   6.95, 7.15 ,  2232, 22.77  ],
[255.00, 4.96 ,   4.80, 5.45 ,  905 ,    23.29  ],
[260.00, 3.29 ,   3.20, 3.40 ,  2090, 21.61  ],
[265.00, 2.19 ,   2.10, 2.19 ,  447 ,    21.13  ],
[270.00, 1.32 ,   1.34, 1.82 ,  323 ,    22.83  ],
[275.00, 0.91 ,   0.84, 0.95 ,  434 ,     21.35    ]
])
P = np.array([
[220.00, 1.89 , 1.64, 1.96 , 514 , 28.21    ],
[225.00, 2.54 ,   2.50, 2.58 ,  352 ,    26.93    ],
[230.00, 3.47 ,   3.35, 3.50 ,  764 ,    26.03    ],
[235.00, 4.65 ,   4.60, 4.70 ,  736 ,    25.16    ],
[240.00, 6.28 ,   6.15, 6.25 ,  1066, 24.34    ],
[245.00, 8.20 ,   8.15, 8.40 ,  615 ,    24.10    ],
[250.00, 11.00, 10.65, 10.75, 223 ,    23.26    ],
[255.00, 13.50, 13.55, 13.80, 441 ,    23.11    ],
[260.00, 17.49, 16.20, 17.25, 104 ,    22.94    ],
[265.00, 20.95, 20.80, 20.95, 2   ,    22.38    ],
[270.00, 26.85, 23.80, 27.30, 1085, 30.48    ],
[275.00, 39.95, 29.60, 29.90, 1   ,    24.20    ],
])
def targ(x):
    s = 0
    for i in range(0,C.shape[0]): 
        s = s + ( blscall(246.58,C[i,0],56,0,x[1])-0.5*(C[i,2]+C[i,3]) )**2 
    for i in range(0,P.shape[0]): 
        s = s + ( blsput(246.58,C[i,0],56,0,x[1])-0.5*(P[i,2]+P[i,3]) )**2 
        return(s)
xopt = fmin(targ, [0.0001,0.01])
print(xopt[0], xopt[1]) 
#s as a function of sigma
N = 2
sigma = np.linspace(0.0,0.01,N)
plt.figure(3)   
#s= sigma.shape what should i do????
plt.plot(sigma,targ)
plt.xlabel('sigma')
plt.ylabel('s')
plt.legend(('call','put'))
plt.show()

您将
targ
定义为一个函数,因此当您执行
plt.pot(sigma,targ)
时,您将在中输入“名称”(对函数的引用)以进行打印,这不是一些可打印的值。您需要使用参数调用
targ
。您的
fmin
调用也是如此


还要注意的是,像您这样使用一个小的
N
,在
linspace

中只会生成两个点,您没有为
target()
函数生成参数。你打算在这个函数中添加什么?另外,您正在使用
targ()
调用绘制一个数据点,这真的是您想要的吗?