How To Plot A Function In Python

In this tutorial, we will learn how to plot a function in Python using two popular libraries, matplotlib and numpy. This knowledge can be useful for creating visualizations to represent complex functions, which can be helpful for many scientific, mathematical, and engineering applications.

Step 1: Install Required Libraries

Before we can plot a function, we need to install two Python libraries, numpy and matplotlib. You can install them using the following command:

The numpy library is used for mathematical operations and handling arrays, while matplotlib is the most widely used library for data visualization in Python.

Step 2: Import Libraries

After installing the requisite libraries, we can now import them in our Python script using the following commands:

Step 3: Define the Function

Now let’s define the function we want to plot. For this tutorial, we will consider the quadratic function, f(x) = x2. You can replace this function with any other function you want to plot.

Step 4: Generate Data Points

Next, we need to generate data points to represent our function. We will use numpy’s linspace function, which generates an evenly spaced array of values over a specified range.

The linspace function takes three arguments: the start of the range, the end of the range, and the number of values between the start and end. In our example, we generate 100 data points between -10 and 10 for the x-values.

Step 5: Plot the Function

Finally, we can use the matplotlib library to plot our function. The commonly used function for plotting is plt.plot().

The above code will generate a plot of our function with labeled axes, a title, and a grid. The function is required to display the plot.



In this tutorial, we learned how to plot a function in Python using the numpy and matplotlib libraries. You can now use these steps to plot any function, and even customize the appearance of your plots further using various options provided by the matplotlib library. Happy plotting!