slopefield.py

Created by tracy-pratt-1

Created on January 09, 2026

2.75 KB

This script will allow you to generate a slope field for a given dy/dx on the x and y axes [-3, 3].

When inputting your dy/dx you must explicitly define every operation

Examples of inputting different slopes are below:

if dy/dx = 2x/y then input 2*x/y

if dy/dx = 0.5x+y then input 0.5*x+y

Watch a tutorial at https://www.youtube.com/watch?v=bT391K229Bs


from matplotlib.pyplot import *
from math import *

# The x-axis minimum is set to -3, change this value to change the window
x_axis_min = -3

# Automatically set the x&y axes based on the x-min 
y_axis_min = x_axis_min
x_axis_max = abs(x_axis_min)
y_axis_max = abs(x_axis_min)
# create a list of x and corresponding y lattice point coordinates using axes max/min
x = list(range(x_axis_min, x_axis_max + 1, 1))  # range(start, stop, step)
y = list(range(x_axis_min, x_axis_max + 1, 1))  # range(start, stop, step)

# allowed math functions for eval
allowed_math = {
    "sqrt": sqrt, "sin": sin, "cos": cos, "tan": tan,
    "log": log, "exp": exp, "pi": pi, "e": e,
    "asin": asin, "acos": acos, "atan": atan,
    "abs": abs, "pow": pow
}

print("Input your dy/dx")
print("-Explicitly define every")
print("operation")
print("Ex: 2x/y input as 2*x/y")

# Ask user for the dydx function
dydx_expression = input("dy/dx= ")

def dydx(_x, _y):
    env = {"x": _x, "y": _y, "__builtins__": {}}
    env.update(allowed_math)
    try:
        return eval(dydx_expression, env)
    except Exception as e:
        print("Error in dydx function:", e)
        return 100

# create list of x, y pairs
x_y = []
xm = []
ym = []

# create nested list of lists of all ordered pairs then extract xm and ym lists
for i in range(len(x)):
    for j in range(len(y)):
        x_y.append((x[i], y[j]))

for i in range(len(x_y)):
    xm.append(x_y[i][0]) # select all x midpoint values

for i in range(len(x_y)):
    ym.append(x_y[i][1]) # select all y midpoint values   

# create x and y axes, extend by 1 in each direction so the slope lines are visible
axis((x_axis_min-1,x_axis_max+1,y_axis_min-1,y_axis_max+1))   # axis(Xmin,Xmax,Ymin,Ymax)
axis("on")                  # mathplotlib: turn axes "on"
grid(False)                 # mathplotlib: turn grid "off"

# mathplotlib: draw arrows(x,y,dx,dy) where (x,y) start and (x + dx, y + dy) is end
# i.e. arrows(xs=xm-dx, ys=ym-dy, 2dx, 2dy)
d  = 0.250 # initial value of half the length of each line segment
xs = []
ys = []
m  = []
dx = []
dy = []

for i in range(len(xm)):
    m.append(dydx(xm[i],ym[i]))  # call dydx to calculate m for each (xm,ym) ordered pair
for i in range(len(xm)):
    dx.append((d)/(sqrt(1 + pow(m[i],2)))) # calculate dx for each xs
for i in range(len(xm)):
    dy.append(m[i] * dx[i])      # calculate dy for each xs
for i in range(len(xm)):
    xs.append(xm[i] - dx[i])     # xs = starting x values of arrows
    ys.append(ym[i] - dy[i])     # ys = starting y values of arrows

# draw arrows starting at each (xs,ys) ordered pair and moving by 2dx and 2dy
for i in range(len(xs)):
  arrow(xs[i],ys[i],2*dx[i],2*dy[i],color="red",head_width = 0.05)

show()  # mathplotlib show display

print("re-execute script to do")
print("another slopefield")

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.