matplotlib ValueError:x和y必须具有相同的第一个维度,但具有形状(100,)和(1,)

xxls0lw8  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(129)

当我试图绘制f_invx时,我得到了主题中的错误。我不知道怎么修。
先谢谢你了。

import sympy
from sympy import *
import matplotlib.pyplot as plt
import numpy as np

这里我计算函数的逆

def calcola_funzione_inversa():

        x, y = sympy.symbols("x y") # definisce x e y come variabili simboliche
        f = Function('f')(x)        # definisce f come una funzione simbolica
        f = (2*x -3)/5

        func = sympy.Eq(y, f)        # pone y = f
        f_inv = sympy.solve(func, x) # risolve la funzione isolando x

        f_invx = f_inv[0].subs(y, x) # sostituisce x a y
        pprint(f_invx)
        return(f_invx)

这里我试着画出一个函数的反函数

def disegna_funzione_inversa(f_invx):

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        x = np.linspace(-4,4,100)

        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_position('zero')
        ax.spines['left'].set_position('zero')

        plt.plot(x, f_invx,  '-r')
        plt.show()

这里我调用函数

f_inversa_in_x = calcola_funzione_inversa()
disegna_funzione_inversa(f_inversa_in_x)
wvyml7n5

wvyml7n51#

这个错误是因为你的“x”在图中是一个numpy。ndarray的长度为100,并且“f_invx”是奇异的“Add”对象。一个简单的方法是使用sympy“lambdify”将“f_inversa_in_x”转换为lambda函数。一个实现可能看起来像这样:

def disegna_funzione_inversa(f_invx):
        # converting sympy expression to lambda funcion
        x = sympy.symbols("x")
        lambdified_f_invx = sympy.lambdify(x, f_invx) 

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        x = np.linspace(-4,4,100)

        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_position('zero')
        ax.spines['left'].set_position('zero')

        plt.plot(x, lambdified_f_invx(x),  '-r')  # lambidified_f_inv_x is a function so we need to feed it argument
        plt.show()

相关问题