是否有一种方法可以绘制“函数字符串”的绘制。在python?

发布于 2025-02-01 20:13:39 字数 1455 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你另情深 2025-02-08 20:13:39

您可以尝试使用输入的X或默认X来使用评估:

import matplotlib.pyplot as plt
import numpy as np
import re


def get_variables(input_string):
    count = 0
    matches = re.findall(r'(?i)[a-z]', input_string)
    return set(matches) #returns unique variables

function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
    pattern = r'\b%s\b' %v
    function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function


if len(variables) == 1:
    plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
    ax = plt.axes(projection="3d")
    ax.plot3D(*varDict.values(),answer) # line
    #ax.scatter3D(*varDict.values(),answer); #scatter
    
plt.show()

如果您想要散点图或添加逻辑以形成形状(即使用meshgrid),则可以更改3D设置,

只需确保评估语句已完全消毒即可。这也要求该函数在Python语法(** not ^)中输入,除非您要添加函数以编辑字符串中的常见语法差异。

You could try using eval with an inputted X or default x:

import matplotlib.pyplot as plt
import numpy as np
import re


def get_variables(input_string):
    count = 0
    matches = re.findall(r'(?i)[a-z]', input_string)
    return set(matches) #returns unique variables

function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
    pattern = r'\b%s\b' %v
    function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function


if len(variables) == 1:
    plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
    ax = plt.axes(projection="3d")
    ax.plot3D(*varDict.values(),answer) # line
    #ax.scatter3D(*varDict.values(),answer); #scatter
    
plt.show()

You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)

Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文