'How to display a plot in PyQt5?
I am new in PyQt5 and I am trying to develop an app that should be able to load a file and display the file's information and create a plot. I used the PyQt5 design to design the app. This is the code created by PyQt5 design:
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>500</width>
<height>350</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>350</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>500</width>
<height>350</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QWidget" name="">
<property name="geometry">
<rect>
<x>30</x>
<y>10</y>
<width>421</width>
<height>311</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="load_file">
<property name="styleSheet">
<string notr="true">background-color: rgb(206, 0, 13);</string>
</property>
<property name="text">
<string>Load file</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="plot">
<property name="styleSheet">
<string notr="true">background-color: rgb(39, 167, 70);</string>
</property>
<property name="text">
<string>Plot</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QTableView" name="tableView"/>
</item>
</layout>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui>
There are two buttons in the app, one to load a file and another one to display a plot. I can load the file but when I press the "Plot" button I need to load the file again. I want to load the file and then be able to press the "Plot" button to show the plot. I also would like to display in the app the data that is inside the file. I used a ViewTable Widget but I don't know how to use it to do what I am looking for. Any idea? This is my code:
from PyQt5 import uic, QtWidgets
import pandas as pd
import matplotlib.pyplot as plt
def load():
load = QtWidgets.QFileDialog.getOpenFileName()[0]
file = pd.read_csv(load, sep=';', decimal=',')
return file
def plot():
x = load()['time']
y = load()['distance']
plt.plot(x,y)
plt.show()
app = QtWidgets.QApplication([])
ui = uic.loadUi('test_file.ui')
ui.load_file.clicked.connect(load)
ui.plot.clicked.connect(plot)
ui.show()
app.exec()
I am using this data just to test.
| time | distance |
|---|---|
| 0 | 0 |
| 1 | 65 |
| 2 | 143 |
| 3 | 212 |
| 4 | 298 |
| 5 | 368 |
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
