-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplotting-gui.py
798 lines (635 loc) · 28.1 KB
/
plotting-gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
"""
Inspired by:
https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_qt_sgskip
https://pyshine.com/Make-GUI-With-Matplotlib-And-PyQt5/
"""
import sys
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from PyQt5 import QtCore, QtWidgets, QtGui, sip
from PyQt5.Qt import Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as Navi
from pathlib import Path
__version__ = "0.0.1"
__author__ = "Nicolas Imstepf"
class ApplicationWindow(QtWidgets.QMainWindow):
"""
Class to create the main window
___________________________________________________
| Toolbar | Open Button |
|_______________________________|_________________|
| Plot | File Explorer |
| | |
| | |
|_______________________________|_________________|
"""
def __init__(self):
super().__init__()
# Debug Mode
# change function of Open Button
self.DEBUG = False
# Window Layout
self.setWindowTitle("Harry Plotter and the Chromatography of Secrets")
# TODO: find serious title
self.setWindowIcon(QtGui.QIcon(str(Path(__file__).parent.resolve() / "src" / "logo.svg")))
self.setWindowState(QtCore.Qt.WindowMaximized)
self._centralWidget = QtWidgets.QWidget(self)
self.setCentralWidget(self._centralWidget)
self.generalLayout = QtWidgets.QGridLayout(self._centralWidget)
self._centralWidget.setLayout(self.generalLayout)
self.generalLayout.setColumnStretch(0, 4)
self.generalLayout.setColumnStretch(1, 1)
# Menubar
self._createMenu()
# Toolbar
self._createToolbar()
# Plot
# initialize values
self.title = "Title"
self.xlabel = "x-axis label"
self.ylabel = "y-axis label"
self.filelistoflist = []
self._createPlot()
# File Explorer
# initialize values
self.filelst = []
self.filelistoflist = []
self.filedict = {}
self.delimiter = ","
self.folderpath = None
self.Nsubplots = None
self.datalst = []
self.Xlist = []
self.Ylist = []
self.LEGENDS = []
self._createExplorer()
# show window
self.show()
def _createMenu(self):
"""
Menubar
Menu
- open folder function
- restart function
- exit function
Delimiter
- select delimiter directly
"""
# open folder function
self.openAct = QtWidgets.QAction("&Open", self)
self.openAct.setShortcut("Ctrl+O")
self.openAct.triggered.connect(self.openfolder)
# restart function
self.restartAct = QtWidgets.QAction("&Restart", self)
self.restartAct.setShortcut("Ctrl+R")
self.restartAct.triggered.connect(self.myRestart)
self.updateAct = QtWidgets.QAction("&Update", self)
self.updateAct.setShortcut("Ctrl+U")
self.updateAct.triggered.connect(self.changedLabels)
# exit function
self.exitAct = QtWidgets.QAction("&Exit", self)
self.exitAct.setShortcut("Ctrl+Q")
self.exitAct.triggered.connect(self.close)
# select Delimiter menu
self.commaAct = QtWidgets.QAction('Comma ","')
self.commaAct.setShortcut("Ctrl+,")
self.commaAct.setCheckable(True)
self.commaAct.setChecked(True)
self.semicolonAct = QtWidgets.QAction('Semicolon ";"')
self.semicolonAct.setShortcut("Ctrl+;")
self.semicolonAct.setCheckable(True)
# group actions of Delimiter-Menu (only one selected delimiter @ time possible)
ag = QtWidgets.QActionGroup(self)
ag.addAction(self.commaAct)
ag.addAction(self.semicolonAct)
# add functions to menubar
self.menu = self.menuBar().addMenu("&Menu")
self.menu.addAction(self.openAct)
self.menu.addAction(self.updateAct)
self.menu.addAction(self.restartAct)
self.menu.addAction(self.exitAct)
self.delimitermenu = self.menuBar().addMenu("&Delimiter")
self.delimitermenu.addAction(self.commaAct)
self.delimitermenu.addAction(self.semicolonAct)
def myRestart(self):
"""
Restart function for the Menubar
called from menu & "Ctrl+R" shortcut
"""
os.execl(sys.executable, sys.executable, *sys.argv)
def _createToolbar(self):
"""
____________________________________________________
| ThemeBox | NaviBox | Open Button |
|_______________|________________|_________________|
"""
self.ToolbarLayout = QtWidgets.QHBoxLayout()
self.generalLayout.addLayout(self.ToolbarLayout, 0, 0)
# create sublayouts
self._createThemeBox()
self._createNaviBox()
self._createOpenFolder()
def _createThemeBox(self):
"""
Combobox to select theme for plotting
sublayout of toolbar
"""
self.themes = ['default', 'bmh', 'classic', 'dark_background', 'fast',
'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright',
'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark',
'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook',
'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk',
'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn',
'Solarize_Light2', 'tableau-colorblind10']
# TODO: minimize after discussion w/ users
self.ThemeBox = QtWidgets.QComboBox()
self.ThemeBox.addItems(self.themes)
self.ToolbarLayout.addWidget(self.ThemeBox)
def _createNaviBox(self):
"""
Matplotlib navigation functions
sublayout of toolbar
"""
self.canv = MatplotlibCanvas(self)
self.toolbar = Navi(self.canv, self._centralWidget)
self.ToolbarLayout.addWidget(self.toolbar)
def _createOpenFolder(self):
"""
Create "Open Folder" button and add it next to the ToolbarLayout
"""
self.OpenBtnLayout = QtWidgets.QHBoxLayout()
openbtn = QtWidgets.QPushButton("Open Folder")
openbtn.clicked.connect(self.openfolder)
self.OpenBtnLayout.addWidget(openbtn)
self.generalLayout.addLayout(self.OpenBtnLayout, 0, 1)
def openfolder(self):
"""
shows Windows Explorer Dialog to select directory
saves directory to self.folderpath
connected with "Open Folder" button & "Ctrl+o" shortcut
"""
options = QtWidgets.QFileDialog.Options()
# Debuggin mode -> set folderpath directly
if self.DEBUG:
self.folderpath = str(Path.cwd())
else:
self.folderpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder', options=options)
if self.folderpath:
self.UpdateTree()
def _createPlot(self):
"""
layout/placeholder for plot
"""
self.PlotLayout = QtWidgets.QVBoxLayout()
self.spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.PlotLayout.addItem(self.spacerItem)
self.generalLayout.addLayout(self.PlotLayout, 1, 0)
self.ThemeBox.currentIndexChanged['QString'].connect(self.Update)
def Update(self, value=None):
"""
creates / updates plot with new data
called by: changedTitle, changedXlabel, changedYlabel, changedLabels, readData
"""
value = self.ThemeBox.currentText()
# close and reset plot
plt.close()
plt.clf()
mpl.rcParams.update(mpl.rcParamsDefault)
# special plotting style
if self.Nsubplots == 42:
self.ToolbarLayout.removeWidget(self.toolbar)
self.PlotLayout.removeWidget(self.canv)
self.xkcdPlot()
return None
# special plotting style
if self.Nsubplots == 0:
self.ToolbarLayout.removeWidget(self.toolbar)
self.PlotLayout.removeWidget(self.canv)
self.myPlot()
return None
if self.filelistoflist:
# use style from themebox
if value is not None and value != "default":
plt.style.use(value)
self.ToolbarLayout.removeWidget(self.toolbar)
self.PlotLayout.removeWidget(self.canv)
# remove toolbar & canvas
sip.delete(self.toolbar)
sip.delete(self.canv)
self.toolbar = None
self.canv = None
self.PlotLayout.removeItem(self.spacerItem)
# create toolbar & canvas
self.canv = MatplotlibCanvas(self, nsubplots=self.Nsubplots)
self.toolbar = Navi(self.canv, self._centralWidget)
self.ToolbarLayout.addWidget(self.toolbar)
self.PlotLayout.addWidget(self.canv)
axs = self.canv.axs
# Colorset according to Bang Wong nature methods | VOL.8 NO.6 | JUNE 2011 | 441
COLORS = {0: (0, 114 / 255, 178 / 255), 1: (0, 158 / 255, 115 / 255), 2: (213 / 255, 94 / 255, 0),
3: (86 / 255, 180 / 255, 233 / 255), 4: (230 / 255, 159 / 255, 0 / 255),
5: (204 / 255, 121 / 255, 167 / 255)}
COLORS.update({i: "black" for i in range(6, 100)}) # unrealistic, but if more than 10 plots are needed
if self.Nsubplots == 1:
# create plot
if value is None or value == "default":
[axs.plot(self.Xlist[0][i]+i*0.1, self.Ylist[0][i]+i*max(self.Ylist[0][0])/5,
label=self.LEGENDS[0][i], color=COLORS[i]) for i in reversed(range(len(self.Xlist[0])))]
else:
[axs.plot(self.Xlist[0][i] + i * 0.1, self.Ylist[0][i] + i * max(self.Ylist[0][0]) / 5,
label=self.LEGENDS[0][i]) for i in reversed(range(len(self.Xlist[0])))]
# add legend (reversed order needed)
# adapted from unutbu stackoverflow.com/questions/34576059/reverse-the-order-of-a-legend
handles, labels = axs.get_legend_handles_labels()
axs.legend(handles[::-1], labels[::-1], frameon=False).set_draggable(True)
else:
# create subplots
for j in range(self.Nsubplots):
if value is None or value == "default":
[axs[j].plot(self.Xlist[j][i]+i*0.1, self.Ylist[j][i]+i*max(self.Ylist[j][0])/5,
label=self.LEGENDS[j][i], color=COLORS[i]) for i in reversed(range(len(self.Xlist[j])))]
else:
[axs[j].plot(self.Xlist[j][i] + i * 0.1, self.Ylist[j][i] + i * max(self.Ylist[j][0]) / 5,
label=self.LEGENDS[j][i]) for i in reversed(range(len(self.Xlist[j])))]
# add legend
handles, labels = axs[j].get_legend_handles_labels()
axs[j].legend(handles[::-1], labels[::-1], frameon=False).set_draggable(True)
# add title (for navibar)
if j == 0:
axs[j].set_title(f"{j+1} (Top)", visible=False)
elif j == self.Nsubplots-1:
axs[j].set_title(f"{j+1} (Bottom)", visible=False)
else:
axs[j].set_title(j+1, visible=False)
# set labels and title
self.canv.fig.suptitle(self.title, fontsize=16)
self.canv.fig.supxlabel(self.xlabel)
self.canv.fig.supylabel(self.ylabel)
self.canv.draw()
def xkcdPlot(self):
"""
creates plot with xkcd style (xkcdPlot class)
called by update
"""
self.PlotLayout.removeItem(self.spacerItem)
self.canv = xkcdPlot(self)
self.PlotLayout.addWidget(self.canv)
self.toolbar = Navi(self.canv, self._centralWidget)
self.ToolbarLayout.addWidget(self.toolbar)
self.canv.draw()
def myPlot(self):
"""
creates plot with my own style (myPlot class)
called by update
"""
self.PlotLayout.removeItem(self.spacerItem)
self.canv = myPlot(self)
self.PlotLayout.addWidget(self.canv)
self.toolbar = Navi(self.canv, self._centralWidget)
self.ToolbarLayout.addWidget(self.toolbar)
self.canv.draw()
def _createExplorer(self):
"""
_________________
| setLabels |
| |
| |
| Tree |
| |
| |
| DragDropList |
| |
| |
| SubplotList |
| |
|_______________|
"""
self.ExplorerLayout = QtWidgets.QVBoxLayout()
self._createSetLabels()
self._createTree()
self._createDragDropList()
self._createSubplots()
# Add scroll area to explorer
scrollwidget = QtWidgets.QWidget()
scrollwidget.setLayout(self.ExplorerLayout)
scroll = QtWidgets.QScrollArea()
scroll.setWidget(scrollwidget)
scroll.setWidgetResizable(True)
self.generalLayout.addWidget(scroll, 1, 1)
def _createSetLabels(self):
"""
Layout to change Labels
"""
self.LabelGroupBox = QtWidgets.QGroupBox("Set Labels")
self.LabelsLayout = QtWidgets.QVBoxLayout()
# Title
self.titleEdit = QtWidgets.QLineEdit()
self.titleEdit.setPlaceholderText("set title")
self.titleEdit.editingFinished.connect(self.changedTitle)
self.LabelsLayout.addWidget(self.titleEdit)
# x label
self.xlabelEdit = QtWidgets.QLineEdit()
self.xlabelEdit.setPlaceholderText("set x-axis label")
self.xlabelEdit.editingFinished.connect(self.changedXlabel)
self.LabelsLayout.addWidget(self.xlabelEdit)
# y label
self.ylabelEdit = QtWidgets.QLineEdit()
self.ylabelEdit.setPlaceholderText("set y-axis label")
self.ylabelEdit.editingFinished.connect(self.changedYlabel)
self.LabelsLayout.addWidget(self.ylabelEdit)
# Update button
self.updatebtn = QtWidgets.QPushButton("Update")
self.updatebtn.clicked.connect(self.Update)
self.LabelsLayout.addWidget(self.updatebtn)
self.LabelGroupBox.setLayout(self.LabelsLayout)
self.ExplorerLayout.addWidget(self.LabelGroupBox)
def changedTitle(self):
"""
changes plot title
linked with titleEdit
"""
self.title = self.titleEdit.text()
self.Update()
def changedXlabel(self):
"""
changes x label
linked with xlabelEdit
"""
self.xlabel = self.xlabelEdit.text()
self.Update()
def changedYlabel(self):
"""
changes y label
linked with ylabelEdit
"""
self.ylabel = self.ylabelEdit.text()
self.Update()
def changedLabels(self):
"""
updates plot
linked with update button
"""
self.Update()
def _createTree(self):
"""
Layout to show files from selected directory
sublayout of Explorer
"""
self.treeGroupBox = QtWidgets.QGroupBox("Raw Data")
self.tree = QtWidgets.QTreeWidget()
self.tree.itemClicked.connect(self.check_status)
self.tree.setHeaderLabels([""])
self.treeLayout = QtWidgets.QVBoxLayout()
self.treeLayout.addWidget(self.tree)
self.treeGroupBox.setLayout(self.treeLayout)
self.ExplorerLayout.addWidget(self.treeGroupBox)
def UpdateTree(self):
"""
Creates tree from selected directory
called by openfolder
"""
self.tree.clear()
self.tree.setHeaderLabels([self.folderpath])
# iteration over data files
for folderName, subfolders, filenames in os.walk(self.folderpath):
parent = QtWidgets.QTreeWidgetItem(self.tree)
parent.setText(0, Path(folderName).name)
parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
for filename in filenames:
if filename[-4:].lower() == ".csv":
child = QtWidgets.QTreeWidgetItem(parent)
child.setText(0, Path(filename).name)
child.setData(0, Qt.UserRole, Path(self.folderpath, folderName, filename))
child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
child.setCheckState(0, Qt.Unchecked)
if parent.childCount() == 0:
parent.setHidden(True)
self.tree.setColumnWidth(0, 800)
def check_status(self):
"""
starts when item of tree is clicked
call/create DragDropList
creates Plot if > 1 item is selected -> readData()
connected with tree.itemClicked
"""
self.filelst = []
root = self.tree.invisibleRootItem()
for i in range(root.childCount()):
subroot = root.child(i)
for j in range(subroot.childCount()):
item = subroot.child(j)
if item.checkState(0) == QtCore.Qt.Checked:
self.filelst.append(item.data(0, Qt.UserRole))
self.DragDropList()
def _createDragDropList(self):
"""
Layout to show selected files
functions
- change order (drag & drop)
- remove items with doubleclick
sublayout of Explorer
"""
self.ddlstGroupBox = QtWidgets.QGroupBox("Selected files")
self.ddlstLayout = QtWidgets.QVBoxLayout()
self.ddlst = QtWidgets.QListWidget()
self.ddlst.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
self.ddlst.setDefaultDropAction(QtCore.Qt.CopyAction)
self.ddlst.doubleClicked.connect(lambda: self.ddlst.takeItem(self.ddlst.currentRow()))
self.ddlstLayout = QtWidgets.QVBoxLayout()
self.ddlstLayout.addWidget(self.ddlst)
self.ddlstGroupBox.setLayout(self.ddlstLayout)
self.ExplorerLayout.addWidget(self.ddlstGroupBox)
def DragDropList(self):
"""
Creates Drag and Drop List from selected files of tree
called by check_status
"""
self.ddlst.clear()
self.filedict = {}
for file in self.filelst:
item = QtWidgets.QListWidgetItem(file.stem)
self.filedict[file.stem] = file
self.ddlst.addItem(item)
self.ddlst.repaint()
def _createSubplots(self):
"""
Creates subplot explorer layout
"""
self.SubplotLayout = QtWidgets.QVBoxLayout()
self.subplotGroupBox = QtWidgets.QGroupBox("Subplots")
self._createSpinBox()
self._createSubplotList()
self.subplotGroupBox.setLayout(self.SubplotLayout)
self.ExplorerLayout.addWidget(self.subplotGroupBox)
def _createSpinBox(self):
"""
Creates spinbox to select number of subplots
"""
self.spinBox = QtWidgets.QSpinBox()
self.spinBox.setValue(1)
self.spinBox.valueChanged.connect(self.getSpinBoxvalue)
self.NsubplotsLayout = QtWidgets.QHBoxLayout()
self.NsubplotsLabel = QtWidgets.QLabel("Number of subplots")
self.Nsubplots = 1
self.NsubplotsLayout.addWidget(self.NsubplotsLabel)
self.NsubplotsLayout.addWidget(self.spinBox)
self.SubplotLayout.addLayout(self.NsubplotsLayout)
def getSpinBoxvalue(self):
"""
read value from spinBox and update subplotLayout according to number of subplots
connected with spinBox.valueChanged
"""
self.Nsubplots = self.spinBox.value()
[self.SubplotLayout.removeWidget(i) for i in self.subplotList]
self._createSubplotList()
def _createSubplotList(self):
"""
Create sublayout of subplotList according to number of subplots
linked to getSpinBoxvalue
"""
self.SubplotListLayout = QtWidgets.QVBoxLayout()
self.subplotList = []
for i in range(self.Nsubplots):
self.subplotList.append(QtWidgets.QListWidget())
self.subplotList[i].setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.subplotList[i].setDefaultDropAction(QtCore.Qt.MoveAction)
self.subplotList[i].doubleClicked.connect(self.removeItem2)
self.subplotList[i].model().rowsMoved.connect(self.updateSubplotOrder)
self.subplotList[i].model().rowsMoved.connect(self.deselectItem)
self.subplotList[i].model().rowsInserted.connect(self.updateSubplotOrder)
self.subplotList[i].model().rowsRemoved.connect(self.updateSubplotOrder)
self.subplotList[i].model().dataChanged.connect(self.updateSubplotOrder)
self.subplotList[i].clicked.connect(lambda: [j.clearSelection() for j in self.subplotList])
self.SubplotListLayout.addWidget(self.subplotList[i])
self.SubplotLayout.addLayout(self.SubplotListLayout)
def updateSubplotOrder(self):
"""
update order of subplots, linked to subplotList (updates if changed)
connected with various subplotList functions (rowsMoved, rowsInserted, rowsRemoved, dataChanged)
"""
self.filelistoflist = []
for j in self.subplotList:
keylist = [j.item(i).text() for i in range(j.count())]
self.filelistoflist.append([self.filedict[i] for i in keylist if i in self.filedict])
self.readData()
def removeItem2(self):
"""
delete items of subplotLists by doubleclicking
connected with subplotList.doubleclicked
"""
for i in self.subplotList:
i.takeItem(i.currentRow())
i.setCurrentRow(-1)
self.updateSubplotOrder()
def deselectItem(self):
"""
deselect items of subplotList
solves problem with deleting multiple items with doubleclick
connected with subplotList.rowsMoved
"""
for i in self.subplotList:
i.setCurrentRow(-1)
def readData(self):
"""
read Data from selected files
updates plot
called by updateSubplotOrder
"""
# set delimiter
if self.commaAct.isChecked():
self.delimiter = ","
else:
self.delimiter = ";"
if self.filelistoflist:
self.datalst = []
self.Xlist = []
self.Ylist = []
self.LEGENDS = []
for j in range(self.Nsubplots):
self.datalst.append({index: np.genfromtxt(i, delimiter=self.delimiter, names=["x", "y"])
for index, i in enumerate(self.filelistoflist[:][j])})
self.Xlist.append({i: self.datalst[j][i]["x"] for i in range(len(self.datalst[j]))})
self.Ylist.append({i: self.datalst[j][i]["y"] for i in range(len(self.datalst[j]))})
self.LEGENDS.append({i: file.stem for i, file in enumerate(self.filelistoflist[j])})
self.Update()
class MatplotlibCanvas(FigureCanvasQTAgg):
"""
Class to create canvas for matplotlib subplots
inspired by https://www.pythonguis.com/tutorials/plotting-matplotlib/
"""
def __init__(self, parent=None, dpi=120, nsubplots=2):
self.nsubplots = nsubplots
# exception handling for 1 plot (no subplots)
if nsubplots == 1:
self.fig, self.axs = plt.subplots(1, 1)
self.axs.spines["top"].set_visible(False)
self.axs.spines["right"].set_visible(False)
else:
self.fig, self.axs = plt.subplots(self.nsubplots, 1, sharex=True)
# self.fig.tight_layout()
self.fig.subplots_adjust(hspace=0.2)
for i in range(nsubplots):
self.axs[i].spines["top"].set_visible(False)
self.axs[i].spines["right"].set_visible(False)
if i != nsubplots-1:
self.axs[i].get_xaxis().set_visible(False)
self.axs[i].spines['bottom'].set_visible(False)
super(MatplotlibCanvas, self).__init__(self.fig)
class xkcdPlot(FigureCanvasQTAgg):
"""
Class to create canvas for matplotlib with xkcd style
https://matplotlib.org/stable/gallery/showcase/xkcd.html#sphx-glr-gallery-showcase-xkcd-py
Based on "Stove Ownership" from XKCD by Randall Munroe https://xkcd.com/418/
"""
def __init__(self, parent=None, dpi=120):
with plt.xkcd():
self.fig = plt.figure()
self.ax = self.fig.add_axes((0.1, 0.2, 0.8, 0.7))
self.ax.spines.right.set_color('none')
self.ax.spines.top.set_color('none')
self.ax.set_xticks([])
self.ax.set_yticks([])
self.ax.set_ylim([-30, 10])
self.data = np.ones(100)
self.data[70:] -= np.arange(30)
self.ax.annotate(
'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))
self.ax.plot(self.data)
self.ax.set_xlabel('time')
self.ax.set_ylabel('my overall health')
# self.fig.tight_layout()
super(xkcdPlot, self).__init__(self.fig)
class myPlot(FigureCanvasQTAgg):
"""
Nicolas favored plotting style
Adapted from https://visme.co/blog/funny-graphs/
"""
def __init__(self, parent=None, dpi=120):
self.fig = plt.figure()
self.ax = self.fig.add_axes((0.1, 0.1, 0.8, 0.8))
self.ax.axis('off')
self.fig.suptitle("my charts and graphs are:", size=20)
self.ax.arrow(0, 1, 0, -2, color='black', head_length=0.07, head_width=0.05, length_includes_head=True)
self.ax.arrow(0, -1, 0, 2, color='black', head_length=0.07, head_width=0.05, length_includes_head=True)
self.ax.arrow(1, 0, -2, 0, color='black', head_length=0.07, head_width=0.05, length_includes_head=True)
self.ax.arrow(-1, 0, 2, 0, color='black', head_length=0.07, head_width=0.05, length_includes_head=True)
self.ax.text(0.5, 1, 'Easy to comprehend', horizontalalignment='center', size=16,
verticalalignment='center', transform=self.ax.transAxes)
self.ax.text(0.5, 0, 'Hard to comprehend', horizontalalignment='center', size=16,
verticalalignment='center', transform=self.ax.transAxes)
self.ax.text(0, 0.5, 'Boring', horizontalalignment='center', size=16,
verticalalignment='center', transform=self.ax.transAxes, rotation='vertical')
self.ax.text(1, 0.5, 'Fascinating', horizontalalignment='center', size=16,
verticalalignment='center', transform=self.ax.transAxes, rotation=270)
self.ax.plot(0.7, 0.7, 'co', markersize=20)
self.ax.text(0.62, 0.76, 'My perception', size=12)
self.ax.plot(-0.7, -0.7, 'mo', markersize=20)
self.ax.text(-0.78, -0.78, 'Everyone else', size=12)
super(myPlot, self).__init__(self.fig)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
view = ApplicationWindow()
sys.exit(app.exec_())