How to Plot a Direction Field with Python

using matplotlib.pyplot.quiver() and straight line equation methods.

Oluwatosin Odubanjo
8 min readDec 27, 2021
Generated with: LibreOffice. Version: 6.4.5.2

keywords: • Python • oneAPI • Direction Field • Differential Equation • Data Parallel Python • Heterogeneous Computing • High Performance Computing
• Intel® Distribution for Python*

1. Direction Field

A Direction Field (DF) is also known as a Slope field, it is a graphical representation of the solutions of differential equations (DEs) of the form:

Generated with: CODECOGS . Version: 3.3

Where f is a function of two variables: x and y.

1.1. Why do we need to plot a Direction Field

To understand the behaviour of a DE and its solutions.

1.2. Behaviour of a Differential Equation

Usually, we want to explore a differential equation to understand the interactions of the variables, that is, the relationships that exist between the variables. Understanding these relationships / interactions is what helps in establishing past, present and future conclusions. Also, the solutions of a DE are a consequence of these relationships / interactions.

2. Constructing a Direction Field

The construction of a Direction Field (DF) is usually the first step in exploring a Differential Equation (DE).

The construction of a DF of a DE does not require that we solve the DE first. We only just have to repeatedly evaluate the given function over a grid of points, which are numerical intervals. Furthermore, DF’s can be constructed for even the most challenging DE’s.

Finally, you need a computer and a suitable application software to repeatedly evaluate a given function over some numerical interval.

2.1. How to construct a Direction Field (DF)

1. Draw a rectangular grid of a few hundred points;

2. Evaluate the given function, (DE), at each point: At each point draw a short line segment whose slope is equal to the value of the function at that point. Each line segment drawn is the tangent to the graph of the solution passing through that point.

3. Creating a Numerical Interval Using numpy.arange()

The numpy.arange() function is used to generate an array of a sequence of numbers of the type integer, float.

sample use of numpy.arange()

See the syntax for the numpy.arange() function here:

4. Drawing a Rectangular Grid of a Few Hundred Points Using numpy.meshgrid()

The numpy.meshgrid() function is used to create a rectangular grid out of two declared one-dimensional arrays.

sample use of numpy.meshgrid()

See the syntax for the numpy.meshgrid() function here:

5. Evaluating a Differential Equation and constructing its Differential Field using matplotlib.pyplot.quiver()

A quiver plot is a type of 2-D plot that is made up of vector lines, these vector lines are in shape of arrows to indicate the direction of the vectors (the lines can however be drawn without arrows). These plots are mainly used to visualize slopes / gradients.

The matplotlibrary quiver() function is used to visualize a vector field over a grid of points which are numerical intervals; the vector at a point represents the magnitude of the field vector at that point.

See the syntax for the matplotlib.pyplot.quiver() function here:

6. Exercise 1: Plot a Direction Field for y’ (x) = x + sin(y)

A. With arrows:

Direction Field for y’(x) = x + sin(y)

B. Without arrows:

Direction Field for y’(x) = x + sin(y)

6.1. Normalization

When plotting the direction field of a differential equation, if we are just particular about the direction, we can make the lines drawn with and without arrows of unit length — this is what is called normalization.

6.2 Normalized Direction Field for y’ (x) = x + sin(y)

A. With arrows:

Normalized Direction Field for y’(x) = x + sin(y)

B. Without arrows:

Normalized Direction Field for y’(x) = x + sin(y)

7. Exercise 2: Plot a Normalized Direction Field for y’ (x) = x^(2) — y

Normalized Direction Field for y’(x) = x^(2)-y

8. Exercise 3: A Falling Object

8.1. Differential Equation (DE) of a falling object

The DE that describes the motion of a falling object in the atmosphere near sea level is given as:

Equation 8.1: DE of a falling object, generated with: CODEGOGS. Version: 3.3

where:

m = mass of the object in kilogram (kg)

dv/dt = acceleration of the object in meter/(second^2)

g = acceleration due to gravity approximately equal to 9.8meter /(second^2)

Cd = Drag coefficient (constant value which varies from one object to another)

v = velocity of the object in meter/second

To solve the equation (8.1) we need to find a function v = v(t) that satisfies the equation. Our concern is to however show how to plot the direction field; to do this, we can assign values to ‘m’ and ‘Cd’. For example, using 10kg and 2 respectively. These values, would simplify the equation to:

Equation 8.2: DE of a specific falling object, generated with: CODEGOGS. Version: 3.3

We can now plot the direction field for equation (8.2):

Generated with: matplotlib.pyplot()

8.2 Equilibrium solution of a Differential Equation (DE)

The equilibrium solution of a DE is also known as the balance solution of the DE. It is obtained when we make the left hand side of the DE equal to zero and then solve for the dependent variable. At the equilibrium solution, the DE is constant with time. For equation (8.2), v(t) = 49, is the equilibrium solution. In the graph above, we see that at value, v(t) = 49, the DE does not change with time.

Now, we plot the equilibrium solution superimposed on the direction field:

Generated with matplotlib.pyplot()

8.3 Python code: Falling Object

The image below shows the python code used in generating the plots for the Direction Field and Equilibrium solution of the Differential Equation of a falling object if mass = 10kg and drag coefficient = 2kg/second.

Python Code: Direction Field and Equilibrium solution for Falling Object

9. Download Python Scripts

The Python scripts used in generating the direction fields used in this post can be downloaded from github using the following steps:

1. Clone repository:

$ git clone https://github.com/olutosinbanjo/plots.git

$ change directory to direction_field folder

OR

2. Download the zip file

$ Go to https://github.com/olutosinbanjo/plots.git

$ Download zip

$ unzip file

$ change directory to direction_field folder

Also, a pdf format of this post can be download from the same github repository :

$ Clone or download zip file

$ change directory to direction_field folder

$ change directory to doc folder

10. Update — extending the quick guide

Intel® DevMesh Project — Direction Field Visualization with Python

The project is an Intel oneAPI project and it is an extension of this medium article.

10.1 Objectives

The scope of this project is mathematics, numerical / scientific computing and high performance computing and the case study differential equation is the differential equation of a falling object.

The overall objective of this project is to demonstrate the visualization of a direction field with Python. Specifically, the project aims to address the following objectives:

O1. To use the differential equation of a falling object as a case study.

O2. To use an open source application software in developing programs for the direction field plot.

O3. To explore the numerical package of the python software (numpy) in developing programs for the direction field plot.

O4. To extend the functionality of the programs developed in O3. with packages provided in the Intel’s Distribution for Python* (IDP*) in order to demonstrate heterogeneous computing.

O5. To explore the possibilities of increasing performance of the python programs developed in 03. with the data parallel package offered by Intel.

10.2 Approach

The implementation of a direction field plot with python is based on two methods:

• The matplotlib.pyplot.quiver() (MPQ) method

• The straight line equation (SLE) method.

I consider these two methods for the purpose of comparison of performance based on the time of execution as well as for the purpose of exploring the following packages in the Intel® Distribution of Python* (IDP*) :

  1. Numpy — an optimized Python numerical package.
  2. The numba.prange expression provided by Numba* — an open-source, NumPy-aware optimizing compiler for Python developed by Anaconda, Inc in collaboration with an open-source community.
  3. SYCL-based XPU programming provided by Data Parallel Python (DPPY).The following packages in DPPY are explored :

• Data Parallel Control (dpctl) — A package for controlling execution on SYCL devices and for SYCL USM data management.

  • Numba_dppy — A standalone extension to Numba adding SYCL kernel programming to Numba*.

10.3 Technologies Used

Development Environment: Intel devcloud — for developing, testing and running the project.

Intel® Hardware: Intel® Xeon® E-2176G.

oneAPI Toolkit(s): oneAPI AI Analytics Toolkit.

Programming Support: Intel® Distribution for Python*.

10.4 Performance results

Performance results obtained show that the best performing program is based on the matplotlib.pyplot.quiver() method, and has the additional functionality of data parallel control (dpctl) package offered by IDP*, enabling it to run on the Integrated Graphics, Intel® UHD Graphics P630 [0x3e96] of the Intel® E-2176G processor.

10.5 Documents and Codes

A full documentation for the project can be obtained on Intel DevMesh and on github.

The python programs used in the project are hosted on github in this repository.

References

  1. W. E. Boyce and R. C. DiPrima, Elementary Differential Equations and Boundary Value Problems, eigth edition. USA: John Wiley & Sons, Inc., 2005.
  2. S. Holzner, Differential Equations For Dummies. Indiana: Wiley Publishing, Inc., 2008.
  3. B. D. Bunday and H. Mulholland, Pure Mathematics for Advanced Level, second edition. Heinemann Educational Books (Nigeria) Plc, 2004.
  4. P. Howard, “Ordinary differential equations in matlab,” 2003.
  5. P. Dawkins, “Paul’s online notes.” [Online]. Available: here.
  6. Mic, “Generate slope fields in r and python,” R-bloggers, 2015. [Online]. Available: here.

Thank you for reading!

--

--

Oluwatosin Odubanjo

Interested in { Computing || Mathematics } -> Physics applications. I enjoy writing.