Page History
...
Parsing of input parameters
Parsing "on knees"
Code Block |
---|
import sys import os def get_input_parameters() : nargs = len(sys.argv) print 'sys.argv[0]: ', sys.argv[0] print 'nargs: ', nargs # Then do something with arguments... |
Use OptionParser
Code Block |
---|
from optparse import OptionParser def input_option_parser() : def_fname = 'spec-xppi0412-r0060-20120507-125420.198726277.txt' def_cols = 100 parser = OptionParser(description='Process optional input parameters.', usage = "usage: %prog [options]") parser.add_option('-f', '--fname', dest='fname', default=def_fname, action='store', type='string', help='input file name') parser.add_option('-c', '--cols', dest='cols', default=def_cols, action='store', type='int', help='number of columns in the image array') parser.add_option('-v', dest='verbose', action='store_true', help='set flag to print more details', default=True) parser.add_option('-q', dest='verbose', action='store_false', help='set flag to print less details') (opts, args) = parser.parse_args() print 'opts:',opts print 'args:',args return (opts, args) |
Manipulation with directories and files
Access to files in the derectory
Code Block |
---|
def getListOfFilesInDir(dirname) : return os.listdir(dirname) def printListOfFilesInDir(dirname) : print 'List of files in the dir.', dirname for name in os.listdir(dirname) : print name print '\n' |
Parsing the pathname
Code Block |
---|
root, ext = os.path.splitext(path) # i.e. path='root-part.tail-part' basename = os.path.basename(path) dirname = os.path.dirname(path) lexist = os.path.lexists(path) isfile = os.path.isfile(path) isdir = os.path.isdir(path) head, tail= os.path.split(path) # i.e. path='head-part/tail-part' ... |
http://docs.python.org/library/os.path.html
Useful string parsing options
http://docs.python.org/library/string.html
...
Python - useful references
Built-in functions
http://docs.python.org/library/functions.html
setattr - gives dynamic variables in python
http://docs.python.org/library/functions.html#setattr
PyQt4
...
Open/close/move other GUI window?
Try to close window if its object exists, othervise - open:
...
Note |
---|
Sometime it looks like the window does not want to move in specified position... |
...
Close window and delete object?
Code Block |
---|
def closeEvent(self, event): try: # try to delete self object in the cp.confpars del cp.confpars.guiconfigparameters except # AttributeError: pass # silently ignore |
...
Code Block |
---|
fig = plt.figure(num=1, figsize=(10,10), dpi=100, facecolor='w',edgecolor='w',frameon=True) axes = fig.add_subplot(111) axim = axes.imshow(arrwin, interpolation='nearest', origin='bottom', aspect='auto', extent=[xmin, xmax, ymax, ymin]) |
...
Clear figure
Code Block |
---|
fig.clear() |
...
Graphic
Code Block |
---|
axes.plot(xarr1, yarr1, '-r', xarr2, yarr2, '-g') |
...
Histogram
Code Block |
---|
axes.hist(arr, bins=100, range=(10,50), log=False) # log for vertical scale only |
...
Image (with colorbar)
Code Block |
---|
img = axes.imshow(arr2d, interpolation='nearest', origin='bottom', aspect='auto') img.set_clim(Amin,Amax) cbar = self.fig.colorbar(img, orientation='vertical', \ fraction=0.1, pad=0.01, shrink=1.0, aspect=20) # fraction - of the 2d plot occupied by the color bar # pad - is a space between 2d image and color bar # shrink - factor for the length of the color bar # aspect - ratio length/width of the color bar |
...
Color bar as a separate sub-plot
Code Block |
---|
axcb = fig.add_axes([0.1, 0.1, 0.8, 0.1]) cbar = fig.colorbar(img, cax=axcb, orientation='horizontal', \ fraction=0.1, pad=0.01, shrink=1.0, aspect=20) axcb.xaxis.set_ticks_position('top') # change position of axis labels |
...
Define subplot(s) with empty axes
Code Block |
---|
axes = fig.add_subplot(111) |
...
Code Block |
---|
axes1 = fig.add_subplot(211) axes2 = fig.add_subplot(212) |
...
Make figure with non-equal subplots
Code Block |
---|
axgr = fig.add_axes([0.1, 0.64, 0.80, 0.35]) axhi = fig.add_axes([0.1, 0.14, 0.35, 0.35]) axti = fig.add_axes([0.55, 0.14, 0.35, 0.35]) |
...
Code Block |
---|
import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(20, 20) # Naive direction [ Y , X ] axsa = fig.add_subplot(gs[ 1:16, 0:14]) axsb = fig.add_subplot(gs[ 1:16, 14:19]) axsc = fig.add_subplot(gs[16: , 0:14]) |
...
Set axes limits
Code Block |
---|
axes.set_xlim((-50,50)) axes.set_ylim((-10,210)) |
...
Draw line
Code Block |
---|
import matplotlib.lines as lines line = lines.Line2D(arrx, arry, linewidth=1, color='r') axes.add_artist(line) |
...
Set a number of ticks along the axis
Code Block |
---|
from matplotlib.ticker import MaxNLocator axes.xaxis.set_major_locator(MaxNLocator(4)) |
...
Axis without tick-labels
Code Block |
---|
import matplotlib.ticker as mtick axes.xaxis.set_major_formatter( mtick.NullFormatter() ) |
...
Rotate axis tick-labels
Code Block |
---|
for label in axes.get_xticklabels() : label.set_rotation(60) # rotate by 60 degree label.set_horizontalalignment('center') # 'right', etc. |
...
Change axis tick-label position on the plot
Code Block |
---|
axes.xaxis.set_ticks_position('top') axes.yaxis.set_ticks_position('right') |
...
Axes labels
Code Block |
---|
axes.set_xlabel('Time index') axes.set_ylabel('dt(sec)') |
...
Text in axes
Code Block |
---|
plt.text(x, y, text, fontsize=7, color='k', ha='left', rotation=45) axes.text(x, y, text, fontsize=7, color='k', ha='left', rotation=45) |
...
Axes title
Code Block |
---|
plt.title('Image',color='b',fontsize=20) or axes.set_title('Image',color='b',fontsize=20) |
...
Window title
Code Block |
---|
fig.canvas.set_window_title('Image And Spectrum ' + u'\u03C6') |
Add unicode symbols in string
Code Block |
---|
str = 'Symbol phi: ' + u'\u03C6' |
...
Get canvas and connect it with mouse buttons
Code Block |
---|
canvas = fig.canvas canvas.mpl_connect('button_press_event', self.processMouseButtonPress) canvas.mpl_connect('button_release_event', self.processMouseButtonRelease) canvas.mpl_connect('motion_notify_event', self.processMouseMotion) ... def processMouseButtonPress(self, event) : print 'MouseButtonPress' print 'event: xdata, ydata, x, y =', event.xdata, event.ydata, event.x, event.y if event.inaxes == self.axgr : self.mousePressOnGraph(event) if event.inaxes == self.axti : self.mousePressOnGraph(event) if event.inaxes == self.axhi : self.mousePressOnHisto(event) if event.button == 1 : # 1=left, 2=middle, 3=right self.gr_xmin = float(event.xdata) |
...
Code Block |
---|
import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt |
...
Get the current matplotlib figure window position on monitor
Code Block |
---|
pos = fig.canvas.manager.window.pos() print 'x,y=', pos.x(), pos.y() |
...
Move the matplotlib figure window in certain (x,y) position
Code Block |
---|
fig.canvas.manager.window.move(x,y) # in pixels from top-left corner |
...
Code Block |
---|
plt.get_current_fig_manager().window.geometry("+100+300") |
...
Move the matplotlib figure window on top (of all pileup windows)
Code Block |
---|
fig.canvas.manager.window.activateWindow() # Makes window active fig.canvas.manager.window.raise_() # Moves window on top |
the attribute trick is that the fig.canvas.manager.window
returns the QtGui.QMainWindow
, which is subclass of QtGui.QWidget
with all that useful methods.
...
Add figure as a widget of the QtGui
Code Block |
---|
fig = plt.figure(num=None figsize=(5,10), dpi=100, facecolor='w',edgecolor='w',frameon=True) vbox = QtGui.QVBoxLayout() vbox.addWidget(fig.canvas) # Wraps figure canvas in widget self.setLayout(vbox) |
How to
...
recieve a signal in program when window is activated by the mouse click on frame ?
I do not know yet...
But, if you click on figure canvas (the region inside the window frame, use
Code Block |
---|
fig.canvas.mpl_connect('button_press_event', self.onButtonPressEvent) #Should be implemented something like: def onButtonPressEvent( self, event ): """Figure is picked""" print 'click on fig number =', event.canvas.figure.number |
...
Receive a signal in program when close window by the click on "X"
Code Block |
---|
fig.canvas.mpl_connect('close_event', self.onCloseEvent) #Should be implemented something like: def onCloseEvent( self, event ): print 'close event, fig number =', event.canvas.figure.number |
...
Close figure from program call
Code Block |
---|
plt.close( num ) # close figure with known number num ... plt.close('all') # close all figures |