当我在作业中使用Matplotlib时,会报告值错误。Matplotlib中第一个维度的代码错误是什么?我如何纠正它?

2024-03-29 11:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

    #A1.1
    import numpy as np
    import scipy.linalg
    import matplotlib.pyplot as plt
    
    L=1
    A=3
    B=2
    N=101
    
    dx = L/(N-1)
    x = np.linspace(0, L, N, endpoint=True)
    xv = np.delete(x, [0,-1])
    AD = A*dx**2
    BD = B*dx**2
    Nv = xv.size
    Dxx = np.zeros((Nv, Nv))
    
    for [i,j], _ in np.ndenumerate(Dxx):
        if i == j:
            Dxx[i,j] = -2 -BD
        elif i == j+1:
            Dxx[i,j] = 1
        elif i == j-1:
            Dxx[i,j] = 1
    
    bv = -AD*np.ones(shape=xv.shape)
    print(Dxx)
    print(bv)
    
    #A1.2
    fv = scipy.linalg.solve(Dxx, bv)
    #f = np.concatenate(([0, fv, [0]]))
    f = np.concatenate((fv, [0]))`enter code here`
    #print(x.shape)
    #print(fv.shape)
    
    #A1.3
    fig, ax = plt.subplots()
    ax.plot(x, f, linewidth=4, color='#008004')
    
    ax.set_xlim([0, 1])
    ax.set_xticks([0, 0.25, 0.5, 0.75, 1])
    ax.set_ylim([0, 0.32])
    ax.set_yticks([0, 0.1, 0.2, 0.3])
    ax.tick_params(axis='both', labelsize=12)
    ax.set_xlabel(r'$x$', fontsize=14)
    ax.set_ylabel(r'$f$', fontsize=14)
    ax.set_title(f"$L$ = {L}", fontsize=14)
    fig.set_size_inches(6, 4)
    plt.tight_layout()
    plt.show()

这是输出:

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-3-7aac3b914b9e> in <module>
         38 #A1.3
         39 fig, ax = plt.subplots()
    ---> 40 ax.plot(x, f, linewidth=4, color='#008004')
         41 
         42 ax.set_xlim([0, 1])
    
    c:\users\thomas\appdata\local\programs\python\python39\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
       1741         """
       1742         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
    -> 1743         lines = [*self._get_lines(*args, data=data, **kwargs)]
       1744         for line in lines:
       1745             self.add_line(line)
    
    c:\users\thomas\appdata\local\programs\python\python39\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
        271                 this += args[0],
        272                 args = args[1:]
    --> 273             yield from self._plot_args(this, kwargs)
        274 
        275     def get_next_color(self):
    
    c:\users\thomas\appdata\local\programs\python\python39\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
        397 
        398         if x.shape[0] != y.shape[0]:
    --> 399             raise ValueError(f"x and y must have same first dimension, but "
        400                              f"have shapes {x.shape} and {y.shape}")
        401         if x.ndim > 2 or y.ndim > 2:
    
    **ValueError: x and y must have same first dimension, but have shapes (101,) and (100,)**'''

我正在matplotlib中做这类作业。在matplotlib中进行打印时,会报告ValueError。我已经检查了拼写错误,但我自己找不到错误。 以上代码就是我的答案。我的代码中导致ValueError的错误是什么?我如何更正它们