user14295847
user14295847

Reputation: 11

Multiple plots of multple ODEs in a single graph using Plotly

I'm trying to include two or more than two plots of differential equations(Scipy.integrate package ODEINT) using Plotly but yet it plots only the initial points instead of the whole plots. [Here is the corresponding output imageI'm tryin to reproduce the plots made in Matplot which is quite trivialHere is the whole code

import numpy as np
from scipy.integrate import odeint
#import plotly.express as px
from plotly.offline import plot
import plotly.graph_objects as G 


# initial condition
y0 = 5.0


# time points
t = np.arange(0,20,1)


# function that returns dy/dt
def model(y,t,k):
    dydt = -k * y
    return dydt



# solve ODEs
k = 0.1
y1 = odeint(model,y0,t,args=(k,))
k = 0.2
y2 = odeint(model,y0,t,args=(k,))
k = 0.5
y3 = odeint(model,y0,t,args=(k,))

fig = G.Figure()

#rows, cols = (3, 20) 
#y = [[0 for i in range(cols)] for j in range(rows)] 

for r in [y1, y2, y3]:
    fig.add_trace(G.Scatter(
        x=t,        
        y=r
        )
    )
     
    
fig.update_layout(title='Sample Graph',
                  xaxis_title='time',
                  yaxis_title='y',
                  template='plotly_white')

# Display figure
fig.show() 
plot(fig)

Upvotes: 1

Views: 306

Answers (1)

user11989081
user11989081

Reputation: 8664

If you flatten the three arrays (y1, y2, y3) your code will work as it is:

import numpy as np
from scipy.integrate import odeint
from plotly.offline import plot
import plotly.graph_objects as G

# initial condition
y0 = 5.0

# time points
t = np.arange(0, 20, 1)

# function that returns dy/dt
def model(y, t, k):
    dydt = -k * y
    return dydt

# solve ODEs
k = 0.1
y1 = odeint(model, y0, t, args=(k,)).flatten()

k = 0.2
y2 = odeint(model, y0, t, args=(k,)).flatten()

k = 0.5
y3 = odeint(model, y0, t, args=(k,)).flatten()

fig = G.Figure()

for r in [y1, y2, y3]:
    fig.add_trace(G.Scatter(
        x=t,
        y=r
    ))

fig.update_layout(title='Sample Graph',
                  xaxis_title='time',
                  yaxis_title='y',
                  template='plotly_white')

# display figure
fig.show()

Upvotes: 1

Related Questions