如何在R中创建斜率场?

4
我开始学习微分方程,并想绘制一些图形。
假设我有 dy/dx = -x / y,如何得到如下斜率场:

slope field

我手动计算了数据,并将其放入数据框中:
library(dplyr)

# creating data manually
x <- c(0, 1, 1, -1, 1)
y <- c(1, 1, 0, -1, -1)
slope <- c(0, -1, NaN, -1, 1)

# putting data in dataframe
data <- data_frame(x, y, slope)

但如何绘制它?

你看过R和Python中生成斜率场的文章吗? - Joseph Wood
https://www.r-bloggers.com/generate-slope-fields-in-r-and-python/ - Scipione Sarlo
还可以搜索“绘制向量场 [r]”。 - IRTFM
1个回答

3

使用来自链接的相同思路,并通过一些改进来控制箭头和网格点的大小:

SlopeField = function(FUN,xi = -5,xs = 5,yi = -5,ys = 5, radius = 0.1, grid.by = 0.25){
  # FUN   - given function ODE i.e:  
  # xi,xs - lower and upper bound - x - plot
  # yi,ys - lower and upper bound - y - plot
  
  # grid points
  seqx = seq(xi,xs,grid.by)
  seqy = seq(yi,ys,grid.by)
  
  # plot
  f = c(xi,xs) 
  h = c(yi,ys)
  plot(f,h,main="Slope field", ylab = "Dependet variable", xlab = "Independet variable", pch = ".")
  
  # arrows
  
  for(x in seqx){
    for(y in seqy){
      ym = y
      xm = x
      
      slope = unlist(FUN(x,y))
      
      if(is.na(slope)){
        cor = "black"
      } else if(slope > 0){
        cor = "blue"
      }else if (slope < 0) {
        cor = "red"
      }else if(slope == 0) {
        cor = "green"
      }
      arrows(radius*cos(atan(slope)+pi)+xm,
             radius*sin(atan(slope)+pi)+ym,
             radius*cos(atan(slope))+xm,
             radius*sin(atan(slope))+ym, 
             length = 0.2*radius, col= cor)
    }
  }
}

创建ODE函数:
ode = function(t, y){
  dydt <- y^2-t
  list(dydt)
}

函数结果:

SlopeField(ode, xi = -2, xs = 5, yi = -2, ys = 2,radius = 0.1, grid.by = 0.25)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接