DEV Community

MeiMeichan
MeiMeichan

Posted on

How can I create a code in python to generate function`s grafics that someone had put an input?

I´m trying to create a very simple program using matplotlib and other libraries to develop a way to generate grafics by inputs, however I´m facing some problems. Do you have any ideia?
Image description

Top comments (1)

Collapse
 
rainleander profile image
Rain Leander

Hello MeiMeiChan,

Your inquiry about creating a Python program for generating function graphs based on user input is an interesting problem. You can certainly accomplish this using libraries like matplotlib for generating the plots, sympy for handling symbolic mathematics, and numpy to create numerical ranges. Here's a simple solution to your problem:

import matplotlib.pyplot as plt
import numpy as np
import sympy as sp

# Function to parse and plot the input
def plot_func():
    # Ask for user input
    user_input = input("Please enter a function of x: ")

    # Symbolic computation
    x = sp.symbols('x')
    func = sp.sympify(user_input)  # Convert the string into a sympy function

    # Generate x values
    x_values = np.linspace(-10, 10, 400)

    # Generate y values using lambdify to convert sympy expression to a function
    func_lambdified = sp.lambdify(x, func, "numpy")  # convert sympy expression to a function
    y_values = func_lambdified(x_values)

    # Create the plot
    plt.plot(x_values, y_values)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title(f'Plot of {user_input}')
    plt.grid(True)
    plt.show()

plot_func()
Enter fullscreen mode Exit fullscreen mode

This Python script will generate a 2D line plot of a function provided by the user. When run, it will ask the user to input a mathematical expression of 'x', such as 'x**2' for a quadratic function or 'sin(x)' for a sine wave. This input is then processed and plotted over the range -10 to 10 on the x-axis.

Specifically, sympy.sympify() is used to convert the input string into a symbolic mathematics expression. The numpy.linspace() function generates an array of 400 points evenly spaced between -10 and 10, which are the x-values at which the function will be evaluated. sympy.lambdify() is then used to convert the symbolic expression into a function that can be evaluated over the numpy array x_values. The resulting y-values are then plotted against the x-values using matplotlib.pyplot.plot(), and the plot is displayed using matplotlib.pyplot.show().

This simple script will need matplotlib, numpy, and sympy libraries installed in your Python environment. If you don't have them installed, you can do so using pip:

pip install matplotlib numpy sympy
Enter fullscreen mode Exit fullscreen mode

This program is a good starting point; you might need to enhance it based on your needs. For instance, this version doesn't handle user input errors, which you might want to consider.

Good luck with your coding!