如何使用 plotly 绘制微分方程

How can I plot a differential equation using plotly

我想使用 but I have not succeeded. I don't know very well how to use that library and for now I have only been able to 使用 plot() 函数绘制上面的代码,但我希望输出是交互式的。

library(deSolve)

## == derivative ==
fn <- function(t, N, r) {
  # dN/dt = r * N
  list(r * N)
}

r <- 1       # Parameter value
N <- 0:100   # sequence of N
t <- 0       # dummy as the derivative is not time dependent

plot(N, fn(t, N, r)[[1]], type="l")

## == integration ==
t <- seq(0, 5, .1)  # time
N0 <- 2             # initial state

## numerical solver
out <- ode(N0, t, fn, r)
plot(out, lwd=2, main="exp")

## for comparison: analytical integration
lines(t, N0*exp(r*t), lwd=2, lty="dotted", col="red")

感谢您的帮助。

一种方法是将 deSolve 对象 out 转换为 , which then can be plotted using 然后 ggplotly (一个 plotly wrapper):

out <- ode(N0, t, fn, r)
out_df <- as.data.frame(ode(N0, t, fn, r))
colnames(out_df)[2] <- "Y" #changing the column name which was `1`. 

#making the ggplot object `ggp` and then using `ggplotly` to make it interactive.
library(ggplot2); library(plotly) ;
ggp <- ggplot(out_df, aes(x = time, y = Y)) + geom_line();
ggplotly(ggp); #check in the `viewer` tab of RStudio, not in the `Plots` tab.

这是你想要的吗?

EDIT 添加行数据在传递到 ggplotly:

之前添加另一个带有 ggp 的 geom_line 层
ggp + geom_line(aes(N0*exp(r*t)), linetype = "dashed", color = "red") + xlim(c(0, 5))

EDIT2 回应 OP 的问题:

你可以了解更多 or in , in this video。要检查您是否有列表,请使用:

is.list(fn(t, N, r))
[1] TRUE

然后 [[1]] returns 第一个 element (可以是另一个列表 :P)

fn(t, N, r)[[1]]
  [1]   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
 [20]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37
 [39]  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56
 [58]  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75
 [77]  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94
 [96]  95  96  97  98  99 100

最后, is an advanced form of a

更紧凑一点:

library("dplyr")
library("ggplot2")
library("plotly")
library("deSolve")

fn <- function(t, N, r) {
  list(r * N)
}

# Note: initial state as named vector y=c(N=2)
ggp <-
  ode(y = c(N = 2), times = seq(0, 5, .1), func = fn, parms = 1) %>% 
  as.data.frame() %>%
  ggplot(aes(x = time, y = N)) + geom_line()

ggplotly(ggp) # check in the `viewer` tab of RStudio, not in the `Plots` tab.