Quyed
Quyed

Reputation: 25

Matplotlib plot not showing line

I'm trying to plot the results of a simple ODE, but the graph line isn't showing in the plot window. See the code below:

import numpy as np
import matplotlib.pyplot as plt


class ForwardEuler_v1(object):
    def __init__(self, f, U0, T, n):
        self.f, self.U0, self.T, self.n = f, U0, T, n
        self.dt = T / float(n)
        self.u = np.zeros(n + 1)
        self.t = np.zeros(n + 1)

    def solve(self):
        """Compute solution for 0 <= t <= T."""
        self.u[0] = float(self.U0)
        self.t[0] = float(0)

        for k in range(self.n):
            self.k = k
            self.t[k + 1] = self.t[k] + self.dt
            self.u[k + 1] = self.advance()
        return self.u, self.t

    def advance(self):
        """Advance the solution one time step."""
        u, dt, f, k, t = self.u, self.dt, self.f, self.k, self.t

        u_new = u[k] + dt * f(u[k], t[k])
        return u_new


def f(u, t):
    return u


solver = ForwardEuler_v1(f, U0=1, T=3, n=15)
u, t = solver.solve()

fig, ax = plt.subplots(1, 1)
ax.plot = (t[0:], u[0:])

plt.show()

The returns from solver.solve() give t with a shape of (16,) and u with a shape of (16,).

Can anyone let me know if this works for them or if I'm plotting this wrong?

Upvotes: 1

Views: 1546

Answers (1)

Sheldore
Sheldore

Reputation: 39042

The problem is that you are not passing the t and u arguments to the plot command. Currently, you are assigning a (t, u) tuple to the plot function and therefore you see an empty graph.

You need to replace the line

ax.plot = (t[0:], u[0:])

by

ax.plot(t[0:], u[0:])

Upvotes: 1

Related Questions