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
Win10Pro Anaconda Python3.7
For the installation of PySimpleGUI, please refer to the previous article Creating a QR code creation GUI with PySimpleGUI.
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'.
Then press'Plot'to plot the graph.
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)
After all it is easy to make!
Recommended Posts