'How to plot the graph of a function depending of time and space
We consider the following funtion depending of $t$ and $x$:
$f(t,x) = e^{-4t\pi^2}\sin(\pi x)$
So, for each time $t$ in the list [0., 0.025, 0.05 , 0.075, 0.1] I would like to plot the graph of the function f(t,.) in Python.
I have tried the following code:
import numpy as np
import matplotlib.pyplot as plt
'time discretization'
dt = 0.025
t = np.arange(0, 0.1 + dt, dt)
m = len(t)
'space discretization'
dx = 0.025
x = np.arange(0, 1 + dx, dx)
n = len(x)
'Matrix E'
E = np.zeros((n,m))
'Loop'
for j in range(0,m-1):
E[:, j ] = np.exp(-4jnp.pi**2)np.sin(np.pix)
'Graphic'
plt.plot(E)
plt.legend([f't = {value}s' for value in t])
However, with the exception of $t = 0$ the graphs displayed after I run the code are completely wrong.
Does some of you have some idea or know some tutorial that can help me to solve this problem?
I thank you in advance for the answer.
Solution 1:[1]
I think you might have a couple problems---one main thing is that when calling plt.plot, you generally want to supply x and y coordinates. Also, you are generating 41 values for x, and 5 values for t, which might lead to issues. But, maybe something like this is what you want?
import numpy as np
import matplotlib.pyplot as plt
def f(t, x):
return np.exp(-4 * t * np.pi ** 2) * np.sin(np.pi * x)
# creating the data
dt = 0.025
t = np.arange(0, 0.1 + dt, dt)
m = len(t)
dx = 0.025
x = np.arange(0, 1 + dx, dx)
# making the plot
plt.figure(figsize=(10, 5))
plt.plot(x, f(0, x), label='t = 0')
for i in range(1, m):
plt.plot(x, f(t[i], x), label=f't = {f[i]}')
plt.xlabel('x')
plt.ylabel('f(t, x)')
plt.legend()
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vstack17 |
