Graph functions in python

How to Plot a Function in Python with Matplotlib

How to Plot a Function in Python with Matplotlib Cover Image

Welcome to this comprehensive tutorial on data visualization using Matplotlib and Seaborn in Python. By working through this tutorial, you will learn to plot functions using Python, customize plot appearance, and export your plots for sharing with others.

Throughout this tutorial, you’ll gain an in-depth understanding of Matplotlib, the cornerstone library for generating a wide array of customizable plots to visualize data effectively. As you become familiar with the basics, we’ll progress to Seaborn. This library builds on Matplotlib’s features and brings clear advantages in terms of visual aesthetics and ease of use.

Here’s a sneak peek of what you’ll learn:

03 Plot Multiple Functions in Matplotlib Using Python

How to Plot a Function in Python Using Matplotlib

In order to plot a function in Python using Matplotlib, we need to define a range of x and y values that correspond to that function. In order to do this, we need to:

  1. Define our function, and
  2. Create a range of continuous x-values and map their corresponding y-values
Читайте также:  Суммирование ряда в питоне

Let’s see how we can accomplish this. First, we’ll need to import our libraries:

# Importing libraries import matplotlib.pyplot as plt import numpy as np

In order to plot a function, we need to import two libraries: matplotlib.pyplot and numpy . We use NumPy in order to apply an entire function to an array more easily.

Let’s now define a function, which will mirror the syntax of f(x) = x ** 2 . We’ll keep things simple for now, simply by squaring our input. Let’s see how we can define this function:

# Define a Function def f(x): return x ** 2

Now that we have a function, let’s define our x-range and y-range. In order to do this, we’ll use the NumPy linspace function, which creates a range of evenly-spaced numbers. Let’s see what this looks like:

# Create x and y Ranges x = np.linspace(-5, 5, 1000) y = f(x)

Because we defined a NumPy array, we can simply pass the array into a function and it will be applied element-wise. Now that we have these arrays, let’s plot our chart:

# Plot the Data plt.plot(x, y) plt.show()

This returns the following image:

01 Plot a Function with Python Using Matplotlib

We can see that the data goes from -5 to +5, though the plot ends before then. Because the function f(x) = x ** 2 actually extends beyond these values, we should modify our plot to be cut off earlier. Let’s see how we can do this:

# Modify the Axes Limits fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(-5, 5) ax.set_ylim(0, 25) plt.show()

Let’s explore what we did in the code block above:

  1. We modified the plot to use the object-oriented approach by using the subplots() function
  2. We then plotted our function on the axes
  3. Finally, we used the .set_xlim() and .set_ylim() methods to modify the bounds of our plot

This returned the following image:

02 - Modify the x and y limits when plotting a function

In the following section, you’ll learn how to customize your plot by adding a legend and title to your functions.

How to Add a Legend and Title to Matplotlib Plots

In this section, you’ll learn how to add a legend describing the function and a title to a Matpltolib plot. In order to do this, let’s go a little wild and define a section function. Take a look at the code block below, where we plot two functions:

# Define an Additional Function def sin(x): return 5 * np.sin(x) # Create x and y values x = np.linspace(-5, 5, 1000) y1 = f(x) y2 = sin(x) # Plot both functions fig, ax = plt.subplots() ax.plot(x, y, label='f(x)=x**2') ax.plot(x, y2, label='f(x)=5sin(x)') ax.set_title('Plotting Functions in Matplotlib', size=14) ax.set_xlim(-5, 5) ax.set_ylim(-5, 25) plt.legend() plt.show()

Let’s break down what we did in the code block above:

  1. We defined a second function and calculated our x-range and y-ranges
  2. We then created our figure and axes and plotted both functions to the axes
  3. Notice that we passed in the label= parameter, which allows you to label the range in the visualization
  4. We then used the .set_title() method to set a title on our plot’s axes

This returns the following image:

03 Plot Multiple Functions in Matplotlib Using Python

Phew! Ok, we’ve been able to plot two functions on the same chart and then add the functions’ descriptions to the plot’s legend. In the following section, you’ll learn how to do this with Seaborn as well.

How to Plot a Function Using Seaborn

In this section, you’ll learn how to use Seaborn to plot two functions. Since this process is very similar to using just Matplotlib, I won’t cover every detail, but rather explain what is different from our Matplotlib implementation. Take a look at the code block below:

import seaborn as sns import numpy as np import pandas as pd import matplotlib.pyplot as plt def f(x): return x ** 2 def sin(x): return 5 * np.sin(x) x = np.linspace(-5, 5, 1000) y1 = f(x) y2 = sin(x) df = pd.DataFrame(zip(x, y1, y2), columns=['x', 'y=f(x)', 'y=5*sin(x)']).set_index('x') fig, ax = plt.subplots() # Plot sns.lineplot() to the ax sns.set_palette('Set2') sns.set_style('ticks') sns.lineplot(df, ax=ax) ax.set_title('Plotting Functions in Matplotlib', size=14) ax.set_xlim(-5, 5) ax.set_ylim(-5, 25) # Despine the graph sns.despine() plt.show()

Let’s break down what we did in the code block above:

  1. We imported Seaborn and Pandas, since we’ll work with a Pandas DataFrame
  2. We declared our two functions and passed the three arrays into the Python zip() function, which allows you to iterate over arrays element-wise
  3. We used some Seaborn helper functions to set a style and a palette, and plotted our two functions using the Seaborn lineplot function. Because our x-values are the DataFrame’s index, we can pass in a wide-format dataset
  4. Finally, we use the Seaborn despine function to remove the top and right borders of our graph

This returns the following image:

Plot Multiple Functions in Python Using Seaborn

This allows us to easily add some styling to our visualization, which would take significantly longer in Matplotlib!

Conclusion

In conclusion, plotting a function using Python’s Matplotlib and Seaborn libraries can be a powerful way to visualize data and gain insights into relationships between variables. By using NumPy’s linspace function, we can easily create x and y values to represent the function. With Matplotlib, we can plot the function, add a title and legend, and customize the appearance of the graph.

Seaborn provides similar capabilities for plotting functions with more advanced statistical analysis and visualization tools (lineplot official documentation). These libraries allow us to quickly and easily generate plots that can help us to better understand our data and make more informed decisions. Overall, understanding how to use these libraries for function plotting is a valuable skill for anyone working with data in Python.

Источник

Plot Mathematical Functions – How to Plot Math Functions in Python?

Plot Mathematical Functions Using Python

Hello folks! In this tutorial, we are going to learn how we can plot mathematical functions using Python. So let’s get started.

Prerequisites

For plotting different mathematical functions using Python, we require the following two Python libraries:

1. NumPy

NumPy is a Python library that supports multi-dimensional arrays & matrices and offers a wide range of mathematical functions to operate on the NumPy arrays & matrices. It is one of the most fundamental libraries for scientific computation. We can install NumPy on our local computer using the following command.

> python -m pip install numpy

2. Matplotlib

Matplotlib is a Python library that is widely used for various types of plotting. Using Matplotlib, We can plot static and interactive visualizations very easily. We can install Matplotlib on our local computer using the following command.

> python -m pip install matplotlib

Steps to Plot Mathematical Functions

First import the numpy and matplotlib.pyplot module in the main Python program (.py) or Jupyter Notebook (.ipynb) using the following Python commands.

import numpy as np import matplotlib.pyplot as plt

For all the plottings, we will follow almost the same steps apart from using the specific NumPy mathematical function in the respective plots.

1. Plot (y = x) Identity function

x = np.arange(0, 11, 1) y = x print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Identity Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [ 0 1 2 3 4 5 6 7 8 9 10] Values of y: [ 0 1 2 3 4 5 6 7 8 9 10]

Identity Function

2. Plot (y = a.x 2 + b.x 2 + c) Quadratic function

x = np.arange(-11, 11, 1) a = 2 b = 9 c = 10 y = a*(x**2) + b*x + c print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Quadratic Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10] Values of y: [153 120 91 66 45 28 15 6 1 0 3 10 21 36 55 78 105 136 171 210 253 300]

Quadratic Function

3. Plot (y = a.x 3 + b.x 2 + c.x + d) Cubic function

x = np.arange(-11, 11, 1) a = 2 b = 3 c = 4 d = 9 y = a*(x**3) + b*(x**2) + c*x + d print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Cubic Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10] Values of y: [-2334 -1731 -1242 -855 -558 -339 -186 -87 -30 -3 6 9 18 45 102 201 354 573 870 1257 1746 2349]

Cubic Function

4. Plot (y = ln(x) or loge(x)) Natural logarithm function

x = np.arange(1, 11, 0.001) y = np.log(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Natural logarithm Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [ 1. 1.001 1.002 . 10.997 10.998 10.999] Values of y: [0.00000000e+00 9.99500333e-04 1.99800266e-03 . 2.39762251e+00 2.39771344e+00 2.39780436e+00]

Natural Log Function

5. Plot (y = log10x) Common/Decimal logarithm function

x = np.arange(1, 11, 0.001) y = np.log10(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Common logarithm Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [ 1. 1.001 1.002 . 10.997 10.998 10.999] Values of y: [0.00000000e+00 4.34077479e-04 8.67721531e-04 . 1.04127423e+00 1.04131372e+00 1.04135320e+00]

Common Log Function

6. Plot (y = e x ) Natural Exponential function

x = np.arange(-11, 11, 0.01) y = np.exp(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Natural exponential Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11. -10.99 -10.98 . 10.97 10.98 10.99] Values of y: [1.67017008e-05 1.68695557e-05 1.70390975e-05 . 5.81045934e+04 5.86885543e+04 5.92783841e+04]

Natural Exponential Function

7. Plot (y = a x ) General Exponential function

x = np.arange(-11, 11, 0.01) a = 8 y = a**x print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("General exponential Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11. -10.99 -10.98 . 10.97 10.98 10.99] Values of y: [1.16415322e-10 1.18861455e-10 1.21358987e-10 . 8.07043896e+09 8.24001604e+09 8.41315629e+09]

General Exponential Function

8. Plot (y = sign(x)) Signum function

x = np.arange(-11, 11, 0.001) y = np.sign(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Signum Function") plt.xlabel("Values of x") plt.ylabel("Values of y)") plt.show()
Values of x: [-11. -10.999 -10.998 . 10.997 10.998 10.999] Values of y: [-1. -1. -1. . 1. 1. 1.]

Signum Function

9. Plot (y = a.sin(b.x + c)) Sinusoidal function in Python

x = np.arange(-11, 11, 0.001) a = 5 b = 3 c = 2 y = a*np.sin(b*x + c) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Sinusoidal Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11. -10.999 -10.998 . 10.997 10.998 10.999] Values of y: [ 2.02018823 2.03390025 2.04759397 . -2.10016104 -2.11376421 -2.12734835]

Sinusoidal Function

10. Plot (y = sinc(x)) Sinc function

x = np.arange(-11, 11, 0.01) y = np.sinc(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Sinc function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11. -10.99 -10.98 . 10.97 10.98 10.99] Values of y: [1.41787526e-16 9.09768439e-04 1.82029537e-03 . 2.73068428e-03 1.82029537e-03 9.09768439e-04]

Sinc Function

11. Plot (y = cosh(x)) Hyperbolic function

x = np.arange(-11, 11, 0.001) y = np.cosh(x) print('Values of x: ', x) print('Values of y: ', y) plt.plot(x, y) plt.title("Hyperbolic Function") plt.xlabel("Values of x") plt.ylabel("Values of y") plt.show()
Values of x: [-11. -10.999 -10.998 . 10.997 10.998 10.999] Values of y: [29937.07086595 29907.14875865 29877.2565585 . 29847.39423524 29877.25655813 29907.14875828]

Hyperbolic Cosin Function

Summing-up

In this tutorial, we have learned how to plot different types of mathematical functions using Numpy and Matplotlib libraries. Hope you have understood the plotting process of different mathematical functions and are ready to experiment on your own. Thanks for reading! Stay tuned with us for amazing learning resources on Python programming.

Источник

Оцените статью