【问题标题】:Matplotlib - Passing an equation through a parameter into a functionMatplotlib - 通过参数将方程传递给函数
【发布时间】:2021-08-08 21:52:19
【问题描述】:

我正在编写一个程序,用户输入一个数学方程(例如 x^2 + 2x + 2),函数 plotFunction 将使用 matplotlib 将其绘制在图表上。 当我输入诸如“x2”之类的参数时,它会返回错误: ValueError:非法格式字符串“x2”;两个标记符号

import matplotlib.pyplot as plt
import numpy as np
class Plotter:
    def __init__(self):
        pass
        
                
    def plotFunction(self, func):     
        x = np.arange(-100, 100)
       
        y = func
        plt.plot(x, y)
        plt.show()

p1 = Plotter()
p1.plotFunction("x**2")

【问题讨论】:

  • 首先欢迎来到 SO。这里有很多问题。您应该学习一些基础知识并查看SymPy 符号数学python 库。你可以用这个库实现你想要的东西。

标签: python matplotlib oop


【解决方案1】:

这并不完全理想,但是,这是我现在想出的。 将 matplotlib.pyplot 导入为 plt

def plot_func():
    three = float(input("X ** 3:\n"))
    two = float(input("X ** 2:\n"))
    one = float(input("X:\n"))
    b = float(input("B:\n"))
    n = -10
    x = []
    y = []
    while n <= 10:
        x.append(n)
        y.append( (three * n) ** 3 + (two * n) ** 2 + (one * n) + b)
        n += 1
    return x, y

x, y = plot_func()
plt.scatter(x, y)
plt.show()

我基本上只是分解了不同的部分,它可以与 x ** 3 以内的任何函数一起使用,当然你可以添加更多。如果您只有 x ** 2 功能,只需让您的 x ** 3 等于 0。同样,这并不理想,但在您找到更好的方法之前它会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2016-09-27
    • 1970-01-01
    • 2016-12-18
    相关资源
    最近更新 更多