When drawing a graph from a function, you may want to see what the graph looks like while changing the parameters. As an example, the comparison between the analytical solution and the numerical solution of the ball coordinates when the ball is thrown vertically, which is described in the following document, can be confirmed while changing the parameters.
Numerical calculation method of fluid mechanics learned with Python
Here, the graph at v0 = 10, 30, 100 is drawn.
Time width: Δt, initial velocity: v0, initial height: h0, gravitational acceleration: g can be changed with the slider. After changing the variable with the slider, draw the graph with the Submit button and delete the graph with the Clear button.
import numpy as np
from matplotlib import pyplot as plt
import PySimpleGUI as sg
layout = [
[
sg.Text(
'delta t',
size=(13, 1)
),
sg.Slider(
(0.01, 1),
0.1,
0.01,
orientation='h',
size=(15, 15),
key='-DELTA T-',
enable_events=True
)
],
[
sg.Text(
'v0',
size=(13, 1)
),
sg.Slider(
(0.01, 100),
10,
0.1,
orientation='h',
size=(15, 15),
key='-V0-',
enable_events=True
)
],
[
sg.Text(
'h0',
size=(13, 1)
),
sg.Slider(
(0, 100),
0,
1,
orientation='h',
size=(15, 15),
key='-H0-',
enable_events=True
)
],
[
sg.Text(
'gravity',
size=(13, 1)
),
sg.Slider(
(0.1, 100),
9.8,
0.1,
orientation='h',
size=(15, 15),
key='-G-',
enable_events=True
)
],
[
sg.Button(
'Submit',
size=(10, 1)
),
sg.Button(
'Clear',
size=(10, 1)
)
]
]
window = sg.Window('Trajectory of ball', layout, location=(0, 0))
Display the graph with matplotlib. After creating the graph area with plt.figure and fig.add_subplot (), turn the main loop. When I monitor GUI events and press the submit button, I read the value from the slider and display the graph. Also, by using plt.pause (), an updatable graph is displayed.
fig = plt.figure(figsize=(7, 7), dpi=100)
ax = fig.add_subplot(111)
while True:
event, values = window.read(timeout=0)
if event == "__TIMEOUT__":
continue
#Exit when the Exit button is pressed or when the window close button is pressed
elif event in ('Exit', sg.WIN_CLOSED, None):
break
elif event == 'Submit':
dt = values['-DELTA T-']
v0 = values['-V0-']
g = values['-G-']
h0 = values['-H0-']
t1 = ((v0 ** 2 + 2 * g * h0) ** 0.5 + v0) / g
t = np.linspace(0, t1, 100)
h = -0.5 * g * t ** 2 + v0 * t + h0
la, = plt.plot(t, h, color='blue')
# ##########################################################
t = 0
h = h0
# h =Change to depiction up to 0
while h >= 0:
ln = plt.scatter(t, h, marker='o', c='black')
h += (-g * t + v0) * dt
t += dt
#Graph depiction
ax.set_xlabel('Time')
ax.set_ylabel('Height')
ax.grid(color='black', linestyle='dashed', linewidth=0.5)
ax.legend(handles=[la, ln], labels=['Analytical', 'Numerical'])
plt.pause(0.1)
# ##########################################################
elif event == 'Clear':
plt.clf()
ax = fig.add_subplot(111)
plt.pause(0.1)
Recommended Posts