[PYTHON] Display the graph while changing the parameters with PySimpleGUI + Matplotlib

Introduction

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.

スクリーンショット 2020-10-26 112924.jpg

GUI display

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))

Graph display

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

Display the graph while changing the parameters with PySimpleGUI + Matplotlib
Display / update the graph according to the input with PySimpleGui
[Python] Set the graph range with matplotlib
Display markers above the border with matplotlib
Increase the font size of the graph with matplotlib
The basis of graph theory with matplotlib animation
Band graph with matplotlib
How to turn off the scale value display while leaving the grid with matplotlib
Put Scipy + Matplotlib in Ubuntu on Vagrant and display the graph with X11 Forwarding
Graph drawing method with matplotlib
Graph Excel data with matplotlib (2)
Real-time graph display by matplotlib
[Python] Read the csv file and display the figure with matplotlib
How to plot a lot of legends by changing the color of the graph continuously with matplotlib
Inference & result display with Tensorflow + matplotlib
Draw a loose graph with matplotlib
Adjust the spacing between figures with Matplotlib
Align the size of the colorbar with matplotlib
[PyQt] Display a multi-axis graph with QtChart
Image display taken with the built-in ISIGHT
Display Python 3 in the browser with MAMP
Display Matplotlib xy graph in PySimple GUI.
Display Japanese graphs with VS Code + matplotlib
Set the xticklabels color individually with matplotlib
Graph trigonometric functions with numpy and matplotlib
When changing the table name with flask_migrate
Match the colorbar to the figure with matplotlib
[Jupyter Notebook memo] Display kanji with matplotlib
Create a graph with borders removed with matplotlib
Mouse over Matplotlib to display the corresponding image
Install matplotlib and display graph on Jupyter Notebook
Draw a flat surface with a matplotlib 3d graph
[Python] limit axis of 3D graph with Matplotlib
Read Python csv data with Pandas ⇒ Graph with Matplotlib
Drawing tips with matplotlib on the server side
I want to display multiple images with matplotlib.
How to display images continuously with matplotlib Note
Draw a graph with matplotlib from a csv file
Graph drawing with jupyter (ipython notebook) + matplotlib + vagrant
Align Matplotlib graph colors with similar colors (color map)
Visualize the behavior of the sorting algorithm with matplotlib
matplotlib: Replace the axis itself with another one.
Display the image after Data Augmentation with Pytorch
[Don't refer to 04.02.17] Display the temperature sensor on a real-time graph with rasberry pi 3.