[PYTHON] Display Matplotlib xy graph in PySimple GUI.

Introduction

I made a program to read a file and display an xy graph by referring to the sample program of PySimpleGUI. Sample program: PySimpleGUI-cookbook-(Recipe-Compare 2 Files), (Matplotlib Window With GUI Window)

Other references Draw a graph with PySimple GUI How to draw a graph with tkinter (pySimpleGUI) without matplotlib

environment

Win10Pro Anaconda Python3.7

For the installation of PySimpleGUI, please refer to the previous article Creating a QR code creation GUI with PySimpleGUI.

Creation program

A program that uploads a CSV file containing x and y data and lets you draw a graph

from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import PySimpleGUI as sg


sg.theme('Light Blue 2')

def draw_plot(x,y):
    plt.plot(x,y)
    plt.show(block=False)
    #block=If you do not specify False, the console will not accept any input during that time, and you will not be able to return to work unless you close the GUI.
    
def check_file(file_name):
    p = Path(file_name)
    print(p.suffix)
    if p.suffix == '.csv':
        df = pd.read_csv(p) 
        x = df.iloc[:,0]
        y = df.iloc[:,1]
        
        return x, y
    
    else:
        print('Wrong data file, data must be CSV')  
        return None, None

layout = [[sg.Text('Enter csv data')],
          [sg.Text('File', size=(8, 1)),sg.Input(key='-file_name-'), sg.FileBrowse()],
          [sg.Submit()],
          [sg.Button('Plot'), sg.Cancel()],
          [sg.Button('Popup')]]

window = sg.Window('Plot', layout)

while True:
    event, values = window.read()
    
    if event in (None, 'Cancel'):
        break
    elif event in 'Submit':
        print('File name:{}'.format(values['-file_name-']))
        x,y = check_file(values['-file_name-'])
        
        if x[0] == None:
            sg.popup('Set file is not CSV')
        
    elif event == 'Plot':
        draw_plot(x,y)
        
    elif event == 'Popup':
        sg.popup('Yes, your application is still running')
window.close()

Run the program and specify the file name. You can select the file by pressing'Browse'on the side. Then press'Submit'. mp1.JPG

Then press'Plot'to plot the graph. Figure_1.png

Click here for the program to create the CSV data used this time. It is the same as the one created in Store various files in HDF5.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def base_func(x,a,b,c):
    y = c + a*(x - b)**2
    return y

x = np.arange(-30, 30, 1)
para = [2.0,5.0,10.0]
np.random.seed(seed=10)
y = base_func(x,para[0],para[1],para[2])+np.random.normal(0, 60, len(x))

plt.scatter(x , y)
plt.show()

#Set data to csv with dataframe
df = pd.DataFrame({'x':x,'y':y})
df.to_csv('csvdata.csv',index=False)

Summary

After all it is easy to make!

Recommended Posts

Display Matplotlib xy graph in PySimple GUI.
Real-time graph display by matplotlib
Draw retention rate graph in Matplotlib
Draw a graph with PySimple GUI
Display LaTeX notation formulas in Python, matplotlib
Bar graph display in pandas (basic edition)
How to suppress display error in matplotlib
Display matplotlib diagrams in a web application
Install matplotlib and display graph on Jupyter Notebook
matplotlib graph album
How to hide user input in PySimple GUI
Put Scipy + Matplotlib in Ubuntu on Vagrant and display the graph with X11 Forwarding
Omit the decimal point of the graph scale in matplotlib
Display the graph while changing the parameters with PySimpleGUI + Matplotlib
Put matplotlib in Centos7.
Graph drawing using matplotlib
Graph drawing in python
View images in Matplotlib
Band graph with matplotlib
2D plot in matplotlib
[GUI in Python] PyQt5-Dialog-
Draw graph in python
Multiple file processing with Kivy + Matplotlib + Draw Graph on GUI
Create SVG graph with matplotlib on heroku (displayed in Japanese)
Graph time series data in Python using pandas and matplotlib
VScode environment construction (on Mac) & graph display in Python (@browser)