Use a new abstract class for dialogs with list of plots.
[pyplotsuite.git] / plotfile2.py
blob3eb029fa7f4cdbb6cf8797298c7243a427de0e5e
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
4 # PlotFile2 -- A tool to make quick plots from data series.
5 # Version: 0.1-alpha (see README)
7 # Copyright (C) 2007 Antonio Ingargiola <tritemio@gmail.com>
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 import sys
15 rootdir = sys.path[0] + '/'
16 sourcedir = rootdir + 'plotfile/'
18 import os.path
19 import gtk
20 from matplotlib.lines import Line2D
21 from common.gtk_generic_windows import \
22 GenericMainPlotWindow, DialogWindowWithCancel,\
23 GenericOpenFileDialog, GenericSecondaryWindow
24 from common.filedata import xyLabelFromFile
25 from numpy import arange, array, min
27 # XML GUI Description file
28 gladefile = sourcedir + 'plotfile2.glade'
30 # Minimum default axis value in log scale when the original value was <= 0
31 LOGMIN = 1e-3
33 # How many centimeter is an inch
34 CM_PER_INCHES = 2.54
36 class DataSet:
37 """An object describing data series with a shared X axis."""
38 def __init__(self, x=None, y1=None, name=None):
39 # self.x is the X axis shared for all y series
40 self.x = x
41 self.len = len(x)
42 self.name = name
44 # self.y is a list of series of data
45 self.y = []
46 if y1 != None: self.add(y1)
48 # self.yline is a list of plotted lines from the current DataSet
49 self.yline = []
51 # Set the plot style, maker and linestyle attributes
52 # Marker and linestyle are separate variables so we can switch them off
53 # and then recover the style information when we turn them on
54 self.marker = '.'
55 self.linestyle = '-'
56 ## TO BE REMOVED
57 ##self.plot_kwargs = dict(
58 ## linestyle = self.linestyle,
59 ## linewidth = 1.5,
60 ## marker = self.marker,
61 ## markersize = 5,
62 ## alpha = 1
63 ## )
65 def add(self, yi):
66 if len(yi) != self.len:
67 raise IndexError, 'Y data length (%d) must be == len(x) (%d)'\
68 % (len(yi), self.len)
69 else:
70 self.y.append(yi)
72 class AxesProperty:
73 """Simple struct to store any properties that has different values for X
74 and Y axes"""
75 x = None
76 y = None
79 # Main window class
81 class PlotFileApp(GenericMainPlotWindow):
82 """
83 This class implements an interactive plot windows with various options.
84 """
85 def __init__(self, x=None, y=None, title='Title', debug=False):
86 GenericMainPlotWindow.__init__(self, 'PlotFileWindow', gladefile)
88 self.set_defaults()
89 self.title = title
90 self.debug = debug
91 self.negative = False
93 self.setup_gui_widgets()
95 # Data: self.data is a list of DataSet() instances
96 if x != None:
97 self.data.append( DataSet(x, y, 'Plot 1') )
98 if min(y) <= 0:
99 self.negative = True
101 # Try to load the file passed as parameter
102 if x == None and y == None:
103 try:
104 self.load(sys.argv[1])
105 except:
106 pass
107 self.plot()
109 def set_defaults(self):
110 # Clear data
111 self.data = []
113 # Plot Defaults
114 self.title = 'Title'
115 self.xlabel = 'X Axis'
116 self.ylabel = 'Y Axis'
117 self.xscale = 'linear'
118 self.yscale = 'linear'
119 self.showPoints = True
120 self.showLines = True
121 self.grid = True
123 # Reset ranges
124 self.xmin, self.xmax, self.ymin, self.ymax = None, None, None, None
125 self.axes_limits = AxesProperty()
126 self.axes_limits.x = dict(linear=None, log=None)
127 self.axes_limits.y = dict(linear=None, log=None)
129 def reset_scale_buttons(self):
130 self.setup = True
131 if self.xscale == 'log':
132 self.xscaleCheckB.set_active(True)
133 else:
134 self.xscaleCheckB.set_active(False)
135 if self.yscale == 'log':
136 self.yscaleCheckB.set_active(True)
137 else:
138 self.yscaleCheckB.set_active(False)
139 self.setup = False
141 def setup_gui_widgets(self):
142 # Create the text entry handler
143 self.xminEntry = self.widgetTree.get_widget('xmin_entry')
144 self.xmaxEntry = self.widgetTree.get_widget('xmax_entry')
145 self.yminEntry = self.widgetTree.get_widget('ymin_entry')
146 self.ymaxEntry = self.widgetTree.get_widget('ymax_entry')
148 # Initialize the check buttons to the correct value
149 self.pointsCheckB = self.widgetTree.get_widget('points_chk_butt')
150 self.linesCheckB = self.widgetTree.get_widget('lines_chk_butt')
151 self.xscaleCheckB = self.widgetTree.get_widget('xlog_chk_butt')
152 self.yscaleCheckB = self.widgetTree.get_widget('ylog_chk_butt')
153 self.reset_scale_buttons()
155 self.cooPickerCheckB = self.widgetTree.get_widget('coordinatePicker')
156 self.moreGridCheckB = self.widgetTree.get_widget('moreGrid')
158 self.window.show_all()
159 if self.debug: print 'end of setup_gui_widgets()'
161 def is_ydata_positive(self):
162 for d in self.data:
163 for yi in d.y:
164 if (yi <= 0).any(): return False
165 return True
167 def plot_data(self, n=0):
168 """Plot the n-th data from the self.data list of DataSet()."""
170 if self.debug: print 'plot_data method'
172 d = self.data[n]
173 d.yline = range(len(d.y))
174 for i, yi in enumerate(d.y):
175 d.yline[i], = self.axis.plot(d.x, yi, ls=d.linestyle,
176 marker=d.marker)
178 self.axis.set_title(self.title)
179 self.axis.set_xlabel(self.xlabel)
180 self.axis.set_ylabel(self.ylabel)
182 self.set_xlim()
183 self.set_ylim()
184 self.canvas.draw()
186 #self.update_axis_limits_entry()
188 def update_axis_limits_entry(self):
190 xmin, xmax = self.axis.get_xlim()
191 self.xminEntry.set_text(str(xmin))
192 self.xmaxEntry.set_text(str(xmax))
194 ymin, ymax = self.axis.get_ylim()
195 self.yminEntry.set_text(str(ymin))
196 self.ymaxEntry.set_text(str(ymax))
200 def plot(self):
201 if self.debug: print 'plot method'
203 if self.yscale == 'log' and not self.is_ydata_positive():
204 self.writeStatusBar('WARNING: Negative Y values in log scale.')
206 self.axis.clear()
208 self.axis.set_yscale('linear')
209 self.axis.set_xscale('linear')
211 for d in self.data:
212 d.yline = range(len(d.y))
213 for i, yi in enumerate(d.y):
214 d.yline[i], = self.axis.plot(d.x, yi, ls=d.linestyle,
215 marker=d.marker)
217 self.axis.set_title(self.title)
218 self.axis.set_xlabel(self.xlabel)
219 self.axis.set_ylabel(self.ylabel)
220 self.axis.grid(self.grid)
222 print 'x', self.xscale, 'y', self.yscale
223 self.axis.set_yscale(self.yscale)
224 self.axis.set_xscale(self.xscale)
226 if len(self.data) > 0:
227 self.set_xlim()
228 if len(self.data[0].y) > 0:
229 self.set_ylim()
231 self.canvas.draw()
233 def set_xlim(self):
234 if self.axes_limits.x[self.xscale] == None:
235 if self.debug: print 'autoscaling...'
236 self.axis.autoscale_view(scalex=True, scaley=False)
237 self.xmin, self.xmax = self.axis.get_xlim()
238 else:
239 if self.debug: print 'using old axis limit', self.axes_limits.x
240 self.xmin, self.xmax = self.axes_limits.x[self.xscale]
241 if self.xscale == 'log':
242 if self.xmin <= 0: self.xmin = LOGMIN
243 if self.xmax <= self.xmin: self.xmax = self.xmin+1
244 self.axis.set_xlim(xmin=self.xmin, xmax=self.xmax)
246 if self.debug: print 'xmin:', self.xmin, 'xmax:', self.xmax
247 self.xminEntry.set_text(str(self.xmin))
248 self.xmaxEntry.set_text(str(self.xmax))
250 def set_ylim(self):
251 if self.axes_limits.y[self.yscale] == None:
252 if self.debug: print 'autoscaling...'
253 self.axis.autoscale_view(scaley=True, scalex=False)
254 self.ymin, self.ymax = self.axis.get_ylim()
255 else:
256 if self.debug: print 'using old axis limit'
257 self.ymin, self.ymax = self.axes_limits.y[self.yscale]
258 if self.yscale == 'log':
259 if self.ymin <= 0: self.ymin = LOGMIN
260 if self.ymax <= self.ymin: self.ymax = self.ymin+1
261 self.axis.set_ylim(ymin=self.ymin, ymax=self.ymax)
263 if self.debug: print 'ymin:', self.ymin, 'ymax:', self.ymax
264 self.yminEntry.set_text(str(self.ymin))
265 self.ymaxEntry.set_text(str(self.ymax))
267 def load(self, filename):
268 try:
269 x, y , xlab, ylab = xyLabelFromFile(filename)
270 except IOError:
271 self.writeStatusBar("Can't open file '%s'" % filename)
272 return False
273 except:
274 self.writeStatusBar("File '%s': file format unknown." % filename)
275 return False
276 else:
277 filename = os.path.basename(filename)
278 self.data.append(DataSet(x,y, filename))
279 self.title = filename
280 if xlab is not None: self.xlabel = xlab
281 if ylab is not None: self.ylabel = ylab
282 self.axes_limits.x = dict(linear=None, log=None)
283 self.axes_limits.y = dict(linear=None, log=None)
284 self.writeStatusBar("File '%s' loaded." % filename)
285 if y.min() <= 0:
286 self.negative = True
287 return True
289 def warn(self, msg):
290 self.writeStatusBar('Warning: '+msg)
293 # The following are menu callback methods
295 def on_title_and_axes_labels_activate(self, widget, *args):
296 TitleAndAxesWindow(self)
299 # The following are GUI callback methods
301 def on_xscale_toggled(self, widget, *args):
302 if not self.setup:
303 self.axes_limits.x[self.xscale] = self.axis.get_xlim()
304 if self.xscaleCheckB.get_active(): self.xscale = 'log'
305 else: self.xscale = 'linear'
306 if self.debug: print "XScale:", self.xscale
307 self.axis.set_xscale(self.xscale)
308 self.set_xlim()
309 self.canvas.draw()
310 self.writeStatusBar('X Axis Scale: %s.' % self.xscale)
313 def on_yscale_toggled(self, widget, *args):
314 if not self.setup:
315 self.axes_limits.y[self.yscale] = self.axis.get_ylim()
316 if self.yscaleCheckB.get_active(): self.yscale = 'log'
317 else: self.yscale = 'linear'
318 if self.debug: print "YScale:", self.yscale
319 self.axis.set_yscale(self.yscale)
320 self.set_ylim()
321 self.canvas.draw()
323 if self.negative and self.yscale == 'log':
324 self.warn('Negative values not displayed in log-scale, lines '+\
325 'may appear discontinuos!')
326 else:
327 self.writeStatusBar('Y Axis Scale: %s.' % self.yscale)
330 def on_points_toggled(self, widget, *args):
331 self.showPoints = not self.showPoints
332 if self.debug: print "Show Points:", self.showPoints
333 for d in self.data:
334 if self.showPoints:
335 # Restore the previous marker style
336 d.yline[0].set_marker(d.marker)
337 else:
338 # Turn off the marker visualization
339 d.yline[0].set_marker('')
340 self.canvas.draw()
342 def on_lines_toggled(self, widget, *args):
343 self.showLines = not self.showLines
344 if self.debug: print "Show Lines:", self.showLines
345 for d in self.data:
346 if self.showLines:
347 # Restore the previous linestyle
348 d.yline[0].set_linestyle(d.linestyle)
349 else:
350 # Turn off the line visualization
351 d.yline[0].set_linestyle('')
352 self.canvas.draw()
354 def on_grid_toggled(self, widget, *args):
355 self.grid = not self.grid
356 if self.debug: print "Show Grid:", self.grid
357 self.axis.grid(self.grid)
358 self.canvas.draw()
360 def on_xmin_entry_activate(self, widget, *args):
361 if self.debug: print 'X Min Entry Activated'
362 s = self.xminEntry.get_text()
363 try:
364 val = float(s)
365 except ValueError:
366 self.statusBar.push(self.context, 'Wrong X axis min limit.')
367 self.xminEntry.set_text('')
368 else:
369 if self.xscale == 'log' and val <= 0:
370 val = LOGMIN
371 self.warn('Only values > 0 are allowed in log scale.')
372 self.xminEntry.set_text(str(val))
373 self.xmin = val
374 self.axis.set_xlim(xmin=val)
375 self.canvas.draw()
377 def on_xmax_entry_activate(self, widget, *args):
378 if self.debug: print 'X Max Entry Activated'
379 s = self.xmaxEntry.get_text()
380 try:
381 val = float(s)
382 except ValueError:
383 self.statusBar.push(self.context, 'Wrong X axis max limit.')
384 self.xmaxEntry.set_text('')
385 else:
386 if self.xscale == 'log' and val <= 0:
387 val = self.xmin*10.0
388 self.warn('Only values > 0 are allowed in log scale.')
389 self.xmaxEntry.set_text(str(val))
390 self.xmax = val
391 self.axis.set_xlim(xmax=val)
392 self.canvas.draw()
394 def on_ymin_entry_activate(self, widget, *args):
395 if self.debug: print 'Y Min Entry Activated'
396 s = self.yminEntry.get_text()
397 try:
398 val = float(s)
399 except ValueError:
400 self.statusBar.push(self.context, 'Wrong Y axis min limit.')
401 self.yminEntry.set_text('')
402 else:
403 if self.yscale == 'log' and val <= 0:
404 val = LOGMIN
405 self.warn('Only values > 0 are allowed in log scale.')
406 self.yminEntry.set_text(str(val))
407 self.ymin = val
408 self.axis.set_ylim(ymin=val)
409 self.canvas.draw()
411 def on_ymax_entry_activate(self, widget, *args):
412 if self.debug: print 'Y Max Entry Activated'
413 s = self.ymaxEntry.get_text()
414 try:
415 val = float(s)
416 except ValueError:
417 self.statusBar.push(self.context, 'Wrong Y axis max limit.')
418 self.ymaxEntry.set_text('')
419 else:
420 if self.yscale == 'log' and val <= 0:
421 val = self.ymin*10.0
422 self.warn('Only values > 0 are allowed in log scale.')
423 self.ymaxEntry.set_text(str(val))
424 self.ymax = val
425 self.axis.set_ylim(ymax=val)
426 self.canvas.draw()
428 def on_apply_button_clicked(self, widget, *args):
429 sxmin = self.xminEntry.get_text()
430 sxmax = self.xmaxEntry.get_text()
431 symin = self.yminEntry.get_text()
432 symax = self.ymaxEntry.get_text()
433 try:
434 xmin_val = float(sxmin)
435 xmax_val = float(sxmax)
436 ymin_val = float(symin)
437 ymax_val = float(symax)
438 except ValueError:
439 self.statusBar.push(self.context, 'Wrong axis limit')
440 else:
441 if self.xscale == 'log':
442 if xmin_val <= 0: xmin_val = LOGMIN
443 if xmax_val <= 0: xmax_val = xmin_val*10
444 if ymin_val <= 0: ymin_val = LOGMIN
445 if ymax_val <= 0: ymax_val = ymin_val*10
446 self.xmin, self.xmax, self.ymin, self.ymax = \
447 xmin_val, xmax_val, ymin_val, ymax_val
448 self.axis.set_xlim(xmin=xmin_val)
449 self.axis.set_xlim(xmax=xmax_val)
450 self.axis.set_ylim(ymin=ymin_val)
451 self.axis.set_ylim(ymax=ymax_val)
452 self.canvas.draw()
455 # The following are MENU callback methods
457 def on_addDataSet_activate(self, widget, *args):
458 OpenFileDialog(self)
459 def on_new_activate(self, widget, *args):
460 self.set_defaults()
461 self.reset_scale_buttons()
462 self.plot()
463 def on_dimensionsResolution_activate(self, widget, *args):
464 DimentionAndResolution(self)
465 def on_autoscale_activate(self, widget, *args):
466 self.axis.autoscale_view()
467 self.canvas.draw()
468 def on_coordinatePicker_activate(self, widget, *args):
469 if self.cooPickerCheckB.get_active():
470 self.cid = self.canvas.mpl_connect('button_press_event',
471 get_coordinates_cb)
472 self.writeStatusBar('Click on the plot to log coordinates on '+\
473 'the terminal.')
474 elif self.cid != None:
475 self.canvas.mpl_disconnect(self.cid)
476 self.writeStatusBar('Coordinate picker disabled.')
477 else:
478 print "Error: tried to disconnect an unexistent event."
479 def on_moreGrid_activate(self, widget, *args):
480 if self.moreGridCheckB.get_active():
481 self.axis.xaxis.grid(True, which='minor', ls='--', alpha=0.5)
482 self.axis.yaxis.grid(True, which='minor', ls='--', alpha=0.5)
483 self.axis.xaxis.grid(True, which='major', ls='-', alpha=0.5)
484 self.axis.yaxis.grid(True, which='major', ls='-', alpha=0.5)
485 else:
486 self.axis.xaxis.grid(False, which='minor')
487 self.axis.yaxis.grid(False, which='minor')
488 self.axis.xaxis.grid(True, which='major', ls=':')
489 self.axis.yaxis.grid(True, which='major', ls=':')
490 self.canvas.draw()
491 def on_info_activate(self, widget, *args):
492 AboutDialog()
493 def on_plot_properties_activate(self, widget, *args):
494 PlotPropertiesDialog(self)
495 def on_makeInterpolation_activate(self, widget, *args):
496 InterpolationDialog(self)
499 def get_coordinates_cb(event):
501 Callback for the coordinate picker tool. This function is not a class
502 method because I don't know how to connect an MPL event to a method instead
503 of a function.
505 if not event.inaxes: return
506 print "%3.4f\t%3.4f" % (event.xdata, event.ydata)
509 # Abstract dialogs classes
511 class DialogWithPlotList(DialogWindowWithCancel):
512 """Abstract class for dialogs with a list of current plots in them."""
514 def __init__(self, dialogName, gladefile, callerApp):
515 DialogWindowWithCancel.__init__(self, dialogName, gladefile, callerApp)
517 self.treeView = self.widgetTree.get_widget('treeview')
518 self.create_plotlist()
520 def create_plotlist(self):
521 # Add a column to the treeView
522 self.addListColumn('Plot List', 0)
524 # Create the listStore Model to use with the treeView
525 self.plotList = gtk.ListStore(str)
527 # Populate the list
528 self.insertPlotList()
530 # Attatch the model to the treeView
531 self.treeView.set_model(self.plotList)
533 def addListColumn(self, title, columnId):
534 """This function adds a column to the list view.
535 First it create the gtk.TreeViewColumn and then set
536 some needed properties"""
538 column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=0)
539 column.set_resizable(True)
540 column.set_sort_column_id(columnId)
541 self.treeView.append_column(column)
543 def insertPlotList(self):
544 for data in self.callerApp.data:
545 self.plotList.append([data.name])
547 def on_applyButton_clicked(self, widget, *args):
548 self.window.destroy()
550 def on_cancelButton_clicked(self, widget, *args):
551 self.window.destroy()
553 def on_okButton_clicked(self, widget, *args):
554 self.window.destroy()
557 # Dialogs classes
559 class InterpolationDialog(DialogWithPlotList):
560 def __init__(self, callerApp):
561 DialogWithPlotList.__init__(self, 'InterpolationDialog',
562 gladefile, callerApp)
565 class PlotPropertiesDialog(DialogWithPlotList):
566 def __init__(self, callerApp):
567 DialogWithPlotList.__init__(self, 'PlotPropertiesDialog',
568 gladefile, callerApp)
570 self.load_widgets()
572 # Retrive the data list
573 self.data = self.callerApp.data
575 # Save all the lines properties in case of Cancell-button
576 self.orig_lines = range(len(self.data))
577 for i,d in enumerate(self.data):
578 self.orig_lines[i] = [Line2D([0], [0]), d.linestyle, d.marker]
579 self.orig_lines[i][0].update_from(d.yline[0])
581 self.selected_data = None
582 self.selected_line = None
583 self.allowReplot = False
585 def load_widgets(self):
586 self.lineWidthSpinButt = \
587 self.widgetTree.get_widget('lineWidthSpinButton')
588 self.lineStyleComboB = \
589 self.widgetTree.get_widget('lineStyleComboBox')
590 self.lineColorComboB = \
591 self.widgetTree.get_widget('lineColorComboBox')
592 self.markerTypeComboB = \
593 self.widgetTree.get_widget('markerTypeComboBox')
594 self.markerSizeSpinButt = \
595 self.widgetTree.get_widget('markerSizeSpinButton')
596 self.markerEdgeColorComboB = \
597 self.widgetTree.get_widget('markerEdgeColComboBox')
598 self.markerFaceColorComboB = \
599 self.widgetTree.get_widget('markerFaceColComboBox')
600 self.markerEdgeWidthSpinButt = \
601 self.widgetTree.get_widget('markerEdgeWidthSpinButton')
603 def update_properties(self):
604 # Set the Spin Buttons with the values for the selected data
605 self.lineWidthSpinButt.set_value(self.selected_line.get_linewidth())
606 self.markerSizeSpinButt.set_value(self.selected_line.get_markersize())
607 mew = self.selected_line.get_markeredgewidth()
608 self.markerEdgeWidthSpinButt.set_value(mew)
610 # Set the Combo Boxes with the values for the selected data
611 self.set_current_linestyle(self.selected_data)
612 self.set_current_marker(self.selected_data)
613 self.set_current_lineColor(self.selected_line)
614 self.set_current_markerEdgeColor(self.selected_line)
615 self.set_current_markerFaceColor(self.selected_line)
617 def set_current_lineColor(self, data_line):
618 lc = data_line.get_color()
619 colors = 'bgrcmyk'
620 if lc in colors:
621 ic = colors.index(lc)
622 self.lineColorComboB.set_active(ic)
623 else:
624 print "WARNING: Unsupported color '%s'." % lc
626 def set_current_markerEdgeColor(self, data_line):
627 mec = data_line.get_mec()
628 colors = 'bgrcmyk'
629 if mec in colors:
630 ic = colors.index(mec)
631 self.lineColorComboB.set_active(ic)
632 else:
633 print "WARNING: Unsupported color '%s'." % mec
635 def set_current_markerFaceColor(self, data_line):
636 mfc = data_line.get_mfc()
637 colors = 'bgrcmyk'
638 if mfc in colors:
639 ic = colors.index(mfc)
640 self.lineColorComboB.set_active(ic)
641 else:
642 print "WARNING: Unsupported color '%s'." % mfc
644 def set_current_linestyle(self, data):
645 ls = data.linestyle
646 line_styles = ['-', '--', ':', '-.']
648 if ls in line_styles:
649 il = line_styles.index(ls)
650 self.lineStyleComboB.set_active(il)
651 else:
652 print "WARNING: Linestyle '%s' not supported." % ls
654 def set_current_marker(self, data):
655 m = data.marker
656 markers = 'os^v<>.+xdDhHp'
657 if m in markers:
658 im = markers.index(m)
659 self.markerTypeComboB.set_active(im)
660 else:
661 print "WARNING: Marker type '%s' not supported." % m
665 # GUI Callbacks
667 def on_treeview_cursor_changed(self, *args):
668 plot_index = self.treeView.get_cursor()[0][0]
669 self.selected_line = self.data[plot_index].yline[0]
670 self.selected_data = self.callerApp.data[plot_index]
672 self.allowReplot = False
673 self.update_properties()
674 self.allowReplot = True
676 def on_lineWidth_value_changed(self, *args):
677 if self.allowReplot and self.selected_line is not None:
678 prop = 'linewidth'
679 lw = self.lineWidthSpinButt.get_value()
681 self.selected_line.set_linewidth(lw)
682 self.callerApp.canvas.draw()
684 def on_lineStyle_changed(self, *args):
685 if self.allowReplot and self.selected_line is not None:
686 if not self.callerApp.linesCheckB.get_active():
687 self.callerApp.linesCheckB.set_active(True)
689 prop = 'linestyle'
690 ls = self.lineStyleComboB.get_active_text()
692 line_styles = {'Continuous': '-', 'Dashed': '--',
693 'Dotted': ':', 'Dot-Line': '-.'}
695 if ls in line_styles.keys():
696 self.selected_line.set_linestyle(line_styles[ls])
697 self.callerApp.canvas.draw()
698 self.selected_data.linestyle = line_styles[ls]
699 else:
700 print "WARNING: Unsupported line style '%s'." % ls
702 def on_lineColor_changed(self, *args):
703 if self.allowReplot and self.selected_line is not None:
704 prop = 'color'
705 text = self.lineColorComboB.get_active_text()
706 color = text[text.find('(') + 1]
708 self.selected_line.set_color(color)
709 self.callerApp.canvas.draw()
711 def on_markerType_changed(self, *args):
712 if self.allowReplot and self.selected_line is not None:
713 if not self.callerApp.pointsCheckB.get_active():
714 self.callerApp.pointsCheckB.set_active(True)
716 prop = 'marker'
717 text = self.markerTypeComboB.get_active_text()
718 m = text[text.find('(') + 1]
720 self.selected_line.set_marker(m)
721 self.callerApp.canvas.draw()
722 self.selected_data.marker = m
724 def on_markerSize_value_changed(self, *args):
725 if self.allowReplot and self.selected_line is not None:
726 prop = 'markersize'
727 ms = self.markerSizeSpinButt.get_value()
729 self.selected_line.set_markersize(ms)
730 self.callerApp.canvas.draw()
732 def on_markerEdgeWidth_value_changed(self, *args):
733 if self.allowReplot and self.selected_line is not None:
734 prop = 'markeredgewidth'
735 mew = self.markerEdgeWidthSpinButt.get_value()
737 self.selected_line.set_markeredgewidth(mew)
738 self.callerApp.canvas.draw()
740 def on_markerEdgeColor_changed(self, *args):
741 if self.allowReplot and self.selected_data is not None:
742 prop = 'markeredgecolor'
743 text = self.markerEdgeColorComboB.get_active_text()
744 color = text[text.find('(') + 1]
746 self.selected_line.set_markeredgecolor(color)
747 self.callerApp.canvas.draw()
749 def on_markerFaceColor_changed(self, *args):
750 if self.allowReplot and self.selected_data is not None:
751 prop = 'markerfacecolor'
752 text = self.markerFaceColorComboB.get_active_text()
753 color = text[text.find('(') + 1]
755 self.selected_line.set_markerfacecolor(color)
756 self.callerApp.canvas.draw()
758 def on_cancelButton_clicked(self, widget, *args):
759 # Restore the old style
760 for orig_line, d in zip(self.orig_lines, self.data):
761 d.yline[0].update_from(orig_line[0])
762 d.linestyle = orig_line[1]
763 d.marker = orig_line[2]
765 self.callerApp.canvas.draw()
766 self.window.destroy()
768 def on_okButton_clicked(self, widget, *args):
769 self.window.destroy()
772 class TitleAndAxesWindow(DialogWindowWithCancel):
774 Dialog for setting Title and axes labels.
776 def __init__(self, callerApp):
777 DialogWindowWithCancel.__init__(self, 'TitleAndAxesWindow', gladefile,
778 callerApp)
780 self.titleEntry = self.widgetTree.get_widget('titleEntry')
781 self.xlabelEntry = self.widgetTree.get_widget('xlabelEntry')
782 self.ylabelEntry = self.widgetTree.get_widget('ylabelEntry')
784 # Update the entries with the current values
785 def sync(field, entry):
786 if field != None: entry.set_text(field)
788 sync(self.callerApp.title, self.titleEntry)
789 sync(self.callerApp.xlabel, self.xlabelEntry)
790 sync(self.callerApp.ylabel, self.ylabelEntry)
792 def on_okButton_clicked(self, widget, *args):
793 print "OK Clicked"
794 self.callerApp.axis.set_title(self.titleEntry.get_text())
795 self.callerApp.axis.set_xlabel(self.xlabelEntry.get_text())
796 self.callerApp.axis.set_ylabel(self.ylabelEntry.get_text())
797 self.callerApp.canvas.draw()
799 self.callerApp.title = self.titleEntry.get_text()
800 self.callerApp.xlabel = self.ylabelEntry.get_text()
801 self.callerApp.ylabel = self.xlabelEntry.get_text()
803 self.window.destroy()
805 class DimentionAndResolution(DialogWindowWithCancel):
807 Dialog for setting Figure dimentions and resolution.
809 def __init__(self, callerApp):
810 DialogWindowWithCancel.__init__(self, 'DimentionsDialog', gladefile,
811 callerApp)
812 self.xdimSpinButton = self.widgetTree.get_widget('xdimSpinButton')
813 self.ydimSpinButton = self.widgetTree.get_widget('ydimSpinButton')
814 self.resolutionSpinButton = self.widgetTree.get_widget(
815 'resolutionSpinButton')
816 self.inchesRadioB = self.widgetTree.get_widget('inRadioButton')
818 self.xdim_o, self.ydim_o = self.callerApp.figure.get_size_inches()
819 self.dpi_o = self.callerApp.figure.get_dpi()
821 self.set_initial_values()
823 def set_values(self, xdim, ydim, dpi):
824 if not self.inchesRadioB.get_active():
825 xdim *= CM_PER_INCHES
826 ydim *= CM_PER_INCHES
827 self.xdimSpinButton.set_value(xdim)
828 self.ydimSpinButton.set_value(ydim)
829 self.resolutionSpinButton.set_value(dpi)
831 def set_initial_values(self):
832 self.set_values(self.xdim_o, self.ydim_o, self.dpi_o)
834 def set_default_values(self):
835 xdim, ydim = rcParams['figure.figsize']
836 dpi = rcParams['figure.dpi']
837 self.set_values(xdim, ydim, dpi)
839 def get_values(self):
840 self.xdim = self.xdimSpinButton.get_value()
841 self.ydim = self.ydimSpinButton.get_value()
842 self.resolution = self.resolutionSpinButton.get_value()
843 if not self.inchesRadioB.get_active():
844 self.xdim /= CM_PER_INCHES
845 self.ydim /= CM_PER_INCHES
847 def set_figsize(self):
848 self.callerApp.figure.set_size_inches(self.xdim, self.ydim)
849 self.callerApp.figure.set_dpi(self.resolution)
851 def on_unity_toggled(self, widget, *args):
852 xdim = self.xdimSpinButton.get_value()
853 ydim = self.ydimSpinButton.get_value()
854 if self.inchesRadioB.get_active():
855 xdim /= CM_PER_INCHES
856 ydim /= CM_PER_INCHES
857 else:
858 xdim *= CM_PER_INCHES
859 ydim *= CM_PER_INCHES
860 self.xdimSpinButton.set_value(xdim)
861 self.ydimSpinButton.set_value(ydim)
863 def on_okButton_clicked(self, widget, *args):
864 print "OK"
865 self.get_values()
866 self.set_figsize()
867 self.callerApp.canvas.draw()
868 self.window.destroy()
870 def on_restoreButton_clicked(self, widget, *args):
871 self.set_default_values()
874 class OpenFileDialog(GenericOpenFileDialog):
876 This class implements the "Open File" dialog.
878 def __init__(self, callerApp):
879 GenericOpenFileDialog.__init__(self, 'OpenFileDialog', gladefile,
880 callerApp)
882 def openSelectedFile(self):
883 loaded = self.callerApp.load( self.filename )
884 if loaded:
885 self.callerApp.plot_data(-1)
886 self.window.destroy()
889 class AboutDialog(GenericSecondaryWindow):
891 Object for the "About Dialog".
893 def __init__(self):
894 GenericSecondaryWindow.__init__(self, 'AboutDialog', gladefile)
895 self.window.set_version(read_version())
898 # Functions
900 def read_version():
901 """ Extract version from README file. """
902 file = open(rootdir+'README')
903 ver = None
904 for line in file:
905 if line.strip().startswith('*Latest Version*'):
906 s = line.split()
907 ver = s[2]
908 break
909 file.close()
910 return ver
912 def test():
913 x = arange(100)
914 y = sin(x/10.0)
915 p = PlotFileApp(x, y, title='Random Sequence', debug=True)
916 p.start()
918 def main():
919 p = PlotFileApp(debug=True)
920 # Try to open a sample file
921 if len(sys.argv) < 2 and os.path.isfile(sourcedir+'samples/data.txt'):
922 p.load(sourcedir+'samples/data.txt')
923 p.plot()
924 p.start()
926 if __name__ == '__main__': main()