Reputation: 19
I want to bring in a text file through PyQt5 and draw a graph with data values.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
from PyQt5.QtGui import QIcon
import numpy as np
import matplotlib.pyplot as plt
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction(QIcon('folder.png'), 'Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Text.txt')
openFile.triggered.connect(self.show)
menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setWindowTitle('File Dialog')
self.setGeometry(300, 300, 300, 200)
self.show()
def show(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', './')
if fname[0]:
f = open(fname[0], 'r')
with f:
data = f.read()
data2=np.array(data)
x=data2[1:,0]
y=data2[1:,1]
plt.plot(x,y)
plt.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Text file photo.
This is the error that appears:
x=data2[1:,0]
IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed
Upvotes: 1
Views: 10237
Reputation: 962
The other answer showed you how to do this correctly, so I'll instead explain what went wrong in your code.
In data = f.read()
, the file is stored as a string instead of an array. If you inspect it, you would see something like x y \n1 2 \n
, with \n
being the newline character. Therefore, data2 = np.array(data)
ends up creating a numpy array containing a single string.
Because your array only has a single item, it has 0 dimensions instead of the two dimensions that you expected.
Upvotes: 0
Reputation: 725
When you use numpy
, you don't need to write your own code to load data from files. Use the numpy
functions to do this for you.
In show()
, I would recommend to change the code like this:
data = np.loadtxt(fname[0], skiprows=1)
x = data[:, 0]
y = data[:, 1]
plt.plot(x, y)
plt.show()
Upvotes: 0