Home > Software design >  Is there a way to plot a "function string" in python?
Is there a way to plot a "function string" in python?

Time:05-27

Example: The user types "(x^2 5)^3" into the terminal and the script plots the function like WolframAlpha would do.

Is there an easy way to do that in python?

The function might include abs(), sqrt() etc.

Thanks in advance for your responses

CodePudding user response:

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.

  • Related