Generate slope fields in R and Python
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Here is a short post on how to generate a quick slope field in R and Python.
If you do not know what a slope field is, well I am not the best person to explain it to you since it is a relative new concept for me as well. From what I’ve understood on the subject, a slope field is a graphical way to sort out a first-order differential equation and get a grasp at the solution without having to solve it analytically.
As the Wikipedia’s page says, “it may be used to qualitatively visualize solutions, or to numerically approximate them.”
In general, I feel safe saying that a slope field is some sort of a graphical approach to a differential equation.
Say you have the following differential equation:
drawing the slope field would look something like this:
In Python (without arrows)
and in R (with arrows, x=f and y=h)
Of course these plots are just very quick and can be improved.
Here is the Python code I used to draw them.
import numpy as np | |
from matplotlib import pyplot as plt | |
# Differential equation | |
# diff = y'= y/x (or say x+y) | |
def diff(x,y): | |
return y/x # try also x+y | |
x = np.linspace(-10,10,50) | |
y = np.linspace(-10,10,50) | |
# use x,y | |
for j in x: | |
for k in y: | |
slope = diff(j,k) | |
domain = np.linspace(j-0.07,j+0.07,2) | |
def fun(x1,y1): | |
z = slope*(domain-x1)+y1 | |
return z | |
plt.plot(domain,fun(j,k),solid_capstyle='projecting',solid_joinstyle='bevel') | |
plt.title("Slope field y'") | |
plt.grid(True) | |
plt.show() | |
print("End of the program") |
And the R code
# Our differential equation | |
diff <- function(x,y) | |
{ | |
return(x/y) #Try also x+y | |
} | |
# Line function | |
TheLine <- function(x1,y1,slp,d) | |
{ | |
z = slope*(d-x1)+y1 | |
return(z) | |
} | |
# Domains | |
x = seq(-20,20,0.5) | |
y = seq(-20,20,0.5) | |
# Points to draw our graph | |
f = c(-5,5) | |
h = c(-5,5) | |
plot(f,h,main="Slope field") | |
# Let's generate the slope field | |
for(j in x) | |
{ | |
for(k in y) | |
{ | |
slope = diff(j,k) | |
domain = seq(j-0.07,j+0.07,0.14) | |
z = TheLine(j,k,slope,domain) | |
arrows(domain[1],z[1],domain[2],z[2],length=0.08) | |
} | |
} |
Here is a beautiful slope field for the following differential equation:
![clip_image002[10] clip_image002[10]](https://i1.wp.com/lh4.ggpht.com/-wfVoyYs27W0/VB9JJCZ8TFI/AAAAAAAAAeg/nDDQspcewbE/clip_image002%25255B10%25255D_thumb%25255B1%25255D.png?resize=67%2C20)
If you need a quick tool for drawing slope fields, this online resource is good, click here.
Hope this was interesting.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.