def SetForPng(proport=0.75, fig_width_pt=455.24, dpi=150, xylabel_fs=9, leg_fs=8, text_fs=9, xtick_fs=7, ytick_fs=7): """ Set figure proportions ====================== """ inches_per_pt = 1.0 / 72.27 # Convert pt to inch fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * proport # height in inches fig_size = [fig_width, fig_height] params = { 'axes.labelsize': xylabel_fs, 'font.size': text_fs, 'legend.fontsize': leg_fs, 'xtick.labelsize': xtick_fs, 'ytick.labelsize': ytick_fs, 'figure.figsize': fig_size, 'savefig.dpi': dpi, } #utl.Ff(&bb, "SetFontSize(%s)\n", args) #utl.Ff(&bb, "rcParams.update({'savefig.dpi':%d})\n", dpi) MPLclose() rcdefaults() rcParams.update(params)
def SetForEps(proport=0.75, fig_width_pt=455.24, xylabel_fs=9, leg_fs=8, text_fs=9, xtick_fs=7, ytick_fs=7): """ Set figure proportions ====================== """ # fig_width_pt = 455.24411 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0/72.27 # Convert pt to inch fig_width = fig_width_pt*inches_per_pt # width in inches fig_height = fig_width*proport # height in inches fig_size = [fig_width,fig_height] #params = {'mathtext.fontset':'stix', # 'cm', 'stix', 'stixsans', 'custom' params = { 'backend' : 'ps', 'axes.labelsize' : xylabel_fs, 'font.size' : text_fs, 'legend.fontsize' : leg_fs, 'xtick.labelsize' : xtick_fs, 'ytick.labelsize' : ytick_fs, 'text.usetex' : True, # very IMPORTANT to avoid Type 3 fonts 'ps.useafm' : True, # very IMPORTANT to avoid Type 3 fonts 'pdf.use14corefonts' : True, # very IMPORTANT to avoid Type 3 fonts 'figure.figsize' : fig_size, } MPLclose() rcdefaults() rcParams.update(params)
def SetForEps(proport=0.75, fig_width_pt=455.24, xylabel_fs=9, leg_fs=8, text_fs=9, xtick_fs=7, ytick_fs=7, text_usetex=True, mplclose=True): """ Set figure proportions ====================== """ # fig_width_pt = 455.24411 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0 / 72.27 # Convert pt to inch fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * proport # height in inches fig_size = [fig_width, fig_height] #params = {'mathtext.fontset':'stix', # 'cm', 'stix', 'stixsans', 'custom' params = { 'backend': 'ps', 'axes.labelsize': xylabel_fs, 'font.size': text_fs, 'legend.fontsize': leg_fs, 'xtick.labelsize': xtick_fs, 'ytick.labelsize': ytick_fs, 'text.usetex': text_usetex, # very IMPORTANT to avoid Type 3 fonts 'ps.useafm': True, # very IMPORTANT to avoid Type 3 fonts 'pdf.use14corefonts': True, # very IMPORTANT to avoid Type 3 fonts 'figure.figsize': fig_size, } if mplclose: MPLclose() rcdefaults() rcParams.update(params)
def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None): if h2o.python_username!='kevin': return import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {'family' : 'normal', 'weight' : 'normal', 'size' : 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot (xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot (xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() if eList or fList: plt.show()
def plot(self): """Plot summary data.""" import pylab pylab.rc('font', size=8) self.plot_measurement(221) self.plot_profile(222) self.plot_real(223) #self.plot_imaginary(223) self.plot_inversion(224) pylab.rcdefaults()
def setPlotOptions(labelsize=20,tickmajor=20,tickminor=10,markersize=10,legendsize=20,legendspacing=1.5,labelsizexy=16): pylab.rcdefaults() pylab.rcParams.update({'xtick.labelsize':labelsizexy,\ 'xtick.major.size':tickmajor,\ 'xtick.minor.size':tickminor,\ 'ytick.labelsize':labelsizexy,\ 'ytick.major.size':tickmajor,\ 'ytick.minor.size':tickminor,\ 'lines.markersize':markersize,\ 'axes.labelsize':labelsize,\ 'legend.fontsize':legendsize,\ 'legend.columnspacing':legendspacing,\ })
def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None, server=False): if h2o.python_username != 'kevin': return # Force matplotlib to not use any Xwindows backend. if server: import matplotlib matplotlib.use('Agg') import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {'family': 'normal', 'weight': 'normal', 'size': 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot(xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() plt.savefig('eplot.jpg', format='jpg') # Image.open('testplot.jpg').save('eplot.jpg','JPEG') if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot(xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() plt.savefig('fplot.jpg', format='jpg') # Image.open('fplot.jpg').save('fplot.jpg','JPEG') if eList or fList: plt.show()
def setPlotOptions(labelsize=22,tickmajor=10,tickminor=7,markersize=10,legendsize=20,legendspacing=1.5,labelsizexy=16): pl.rcdefaults() pl.rcParams.update({'xtick.labelsize':labelsizexy, 'xtick.major.size':tickmajor, 'xtick.minor.size':tickminor, 'ytick.labelsize':labelsizexy, 'ytick.major.size':tickmajor, 'ytick.minor.size':tickminor, 'lines.markersize':markersize, 'axes.labelsize':labelsize, 'legend.fontsize':legendsize, 'legend.columnspacing':legendspacing, 'lines.linewidth': 1.5, 'figure.autolayout': True, })
def setPlotOptions(labelsize=20,tickmajor=20,tickminor=10,markersize=10,legendsize=20,legendspacing=1.5,labelsizexy=16): """ set plot label size, tick size, line size, markersize """ pylab.rcdefaults() pylab.rcParams.update({'xtick.labelsize':labelsizexy,\ 'xtick.major.size':tickmajor,\ 'xtick.minor.size':tickminor,\ 'ytick.labelsize':labelsizexy,\ 'ytick.major.size':tickmajor,\ 'ytick.minor.size':tickminor,\ 'lines.markersize':markersize,\ 'axes.labelsize':labelsize,\ 'legend.fontsize':legendsize,\ 'legend.columnspacing':legendspacing,\ })
def plotLists( xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None, server=False ): if h2o.python_username != "kevin": return # Force matplotlib to not use any Xwindows backend. if server: import matplotlib matplotlib.use("Agg") import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {"family": "normal", "weight": "normal", "size": 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot(xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() plt.savefig("eplot.jpg", format="jpg") # Image.open('testplot.jpg').save('eplot.jpg','JPEG') if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot(xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() plt.savefig("fplot.jpg", format="jpg") # Image.open('fplot.jpg').save('fplot.jpg','JPEG') if eList or fList: plt.show()
def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None, server=False): if h2o_args.python_username!='kevin': return # Force matplotlib to not use any Xwindows backend. if server: import matplotlib matplotlib.use('Agg') import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {'family' : 'normal', 'weight' : 'normal', 'size' : 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot (xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() plt.savefig('eplot.jpg',format='jpg') # Image.open('testplot.jpg').save('eplot.jpg','JPEG') if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot (xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() plt.savefig('fplot.jpg',format='jpg') # Image.open('fplot.jpg').save('fplot.jpg','JPEG') if eList or fList: plt.show()
def sampling_structure(self, **kw): '''Plot the response into the file in the fig subdirectory. ''' if self.plot_mode == 'subplots': p.rcdefaults() else: fsize = 28 p.rcParams['font.size'] = fsize rc('legend', fontsize=fsize - 8) rc('axes', titlesize=fsize) rc('axes', labelsize=fsize + 6) rc('xtick', labelsize=fsize - 8) rc('ytick', labelsize=fsize - 8) rc('xtick.major', pad=8) for i, s in enumerate(self.sampling_lst): self._plot_sampling(i, len(self.sampling_lst), sampling_type=s, **kw) if self.show_output: p.show()
def setPlotOptions( labelsize=20, tickmajor=20, tickminor=10, markersize=10, legendsize=20, legendspacing=1.5, labelsizexy=16 ): """ set plot label size, tick size, line size, markersize """ pylab.rcdefaults() pylab.rcParams.update( { "xtick.labelsize": labelsizexy, "xtick.major.size": tickmajor, "xtick.minor.size": tickminor, "ytick.labelsize": labelsizexy, "ytick.major.size": tickmajor, "ytick.minor.size": tickminor, "lines.markersize": markersize, "axes.labelsize": labelsize, "legend.fontsize": legendsize, "legend.columnspacing": legendspacing, } )
def SetForPng(proport=0.75, fig_width_pt=455.24, dpi=150, xylabel_fontsize=9, leg_fontsize=8, text_fontsize=9, xtick_fontsize=7, ytick_fontsize=7): """ Set figure proportions ====================== """ inches_per_pt = 1.0/72.27 # Convert pt to inch fig_width = fig_width_pt*inches_per_pt # width in inches fig_height = fig_width*proport # height in inches fig_size = [fig_width,fig_height] params = { 'axes.labelsize' : xylabel_fontsize, 'font.size' : text_fontsize, 'legend.fontsize' : leg_fontsize, 'xtick.labelsize' : xtick_fontsize, 'ytick.labelsize' : ytick_fontsize, 'figure.figsize' : fig_size, 'savefig.dpi' : dpi, } MPLclose() rcdefaults() rcParams.update(params)
def SetForPng(proport=0.75, fig_width_pt=455.24, dpi=150, xylabel_fs=9, leg_fs=8, text_fs=9, xtick_fs=7, ytick_fs=7): """ Set figure proportions ====================== """ inches_per_pt = 1.0 / 72.27 # Convert pt to inch fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * proport # height in inches fig_size = [fig_width, fig_height] params = { "axes.labelsize": xylabel_fs, "font.size": text_fs, "legend.fontsize": leg_fs, "xtick.labelsize": xtick_fs, "ytick.labelsize": ytick_fs, "figure.figsize": fig_size, "savefig.dpi": dpi, } # utl.Ff(&bb, "SetFontSize(%s)\n", args) # utl.Ff(&bb, "rcParams.update({'savefig.dpi':%d})\n", dpi) MPLclose() rcdefaults() rcParams.update(params)
def SetForEps( proport=0.75, fig_width_pt=455.24, xylabel_fs=9, leg_fs=8, text_fs=9, xtick_fs=7, ytick_fs=7, text_usetex=True, mplclose=True, ): """ Set figure proportions ====================== """ # fig_width_pt = 455.24411 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0 / 72.27 # Convert pt to inch fig_width = fig_width_pt * inches_per_pt # width in inches fig_height = fig_width * proport # height in inches fig_size = [fig_width, fig_height] # params = {'mathtext.fontset':'stix', # 'cm', 'stix', 'stixsans', 'custom' params = { "backend": "ps", "axes.labelsize": xylabel_fs, "font.size": text_fs, "legend.fontsize": leg_fs, "xtick.labelsize": xtick_fs, "ytick.labelsize": ytick_fs, "text.usetex": text_usetex, # very IMPORTANT to avoid Type 3 fonts "ps.useafm": True, # very IMPORTANT to avoid Type 3 fonts "pdf.use14corefonts": True, # very IMPORTANT to avoid Type 3 fonts "figure.figsize": fig_size, } if mplclose: MPLclose() rcdefaults() rcParams.update(params)
"""DisasterModel time series""" from pymc.examples import DisasterModel import pylab as P import numpy as np y = DisasterModel.disasters_array years = 1852 + np.arange(len(y)) P.rcdefaults() P.figure(figsize=(6,3)) P.subplots_adjust(bottom=.2) P.subplot(111) P.plot(years, y, 'bo', ms=3) P.plot(years, y, 'k-', lw=1, alpha=.5) P.xlim(years.min(), years.max()) P.xlabel('Year') P.ylabel('Number of disasters') P.savefig('disastersts_web.png', dpi=80) P.close() P.figure(figsize=(6,3)) P.rcParams['font.size'] = 10. P.subplots_adjust(bottom=.2) P.subplot(111) P.plot(years, y, 'ko', ms=3) P.plot(years, y, 'k-', lw=1, alpha=.5) P.xlim(years.min(), years.max())
import pylab as pl import numpy as np import csv pl.rcdefaults() pl.rc('text', usetex=False) #pl.rc('font', family='sans-serif') with open('trace.csv', 'r') as f: reader = csv.reader(f) entries = list(reader) #convert data to float, skip first line which contains headers data = [[float(c) for c in r] for r in entries[1:]] #transpose into a numpy array data = np.transpose(np.array(data)) with open('trace2.csv', 'r') as f: reader = csv.reader(f) entries = list(reader) #convert data to float, skip first line which contains headers data2 = [[float(c) for c in r] for r in entries[1:]] #transpose into a numpy array data2 = np.transpose(np.array(data2)) #theory t = data[0]
def fakephot(fakefilename, outfilename=None): """ collect photometry for all fakes in the image, make plots of input vs output positions and mags """ import os fakeroot = os.path.splitext(os.path.basename(fakefilename))[0] from pylab import rcParams, rcdefaults from math import sqrt rcParams['lines.linewidth'] = 1.5 rcParams['font.size'] = 15 # text big enough for a half-page fig rcParams['axes.labelsize'] = 15 # fontsize of the x and y labels if outfilename == None: outfilename = fakefilename.replace('.fits', '_fakephot.pdf') # construct coord and mag lists from the fits header keywords coordlist, xin, yin, magin = [], [], [], [] hdr = pyfits.getheader(fakefilename) for key in hdr.keys(): if (key.startswith('FAKE') and key.endswith('X')): xin.append(hdr[key]) if (key.startswith('FAKE') and key.endswith('Y')): yin.append(hdr[key]) if (key.startswith('FAKE') and key.endswith('M')): magin.append(hdr[key]) for i in range(len(xin)): coordlist.append((xin[i], yin[i])) # collect forced photometry at fixed positions (for checking mags) forced = run(fakefilename, coordlist, WCS=False, outroot=fakeroot + '_forced', calgorithm='none', poisson=True, smallskyann=False) # collect photometry with recentering allowed (for checking positions) free = run(fakefilename, coordlist, WCS=False, outroot=fakeroot + '_free', poisson=True, smallskyann=False) # compute residuals dx = free['x'] - xin dy = free['y'] - yin dmag = forced['mag'] - magin dmag = nan_to_num(dmag) # make some plots from matplotlib.pyplot import figure, clf, savefig, autoscale # autoscale( enable=True, axis='both', tight=False ) fig = figure(1, figsize=[8.5, 11]) ax1 = fig.add_subplot(3, 2, 1) ax1.plot(xin, dx, 'ro', ls=' ') ax1.set_ylabel('$x_{out}-x_{in}$') ax1.set_xlabel('$x_{in}$') ax1.axhline(0, color='0.3', lw=0.7) ax2 = fig.add_subplot(3, 2, 2) ax2.plot(yin, dy, 'ro', ls=' ') ax2.set_ylabel('$y_{out}-y_{in}$') ax2.set_xlabel('$y_{in}$') ax2.axhline(0, color='0.3', lw=0.7) ax3 = fig.add_subplot(3, 2, 3) ax3.plot(magin, forced['mag'], 'bs', ls=' ') ax3.plot([max(magin), min(magin)], [max(magin), min(magin)], 'k-') ax3.errorbar(magin, forced['mag'], forced['magerr'], marker='s', color='b', ls=' ') ax3.set_ylabel('$m_{out}$') ax3.set_xlabel('$m_{in}$') #bins,edges = histogram( dmag, bins=max(10, len(dmag)/10) ) ax4 = fig.add_subplot(3, 2, 4) histout = ax4.hist(dmag, bins=max(5, sqrt(len(magin))), align='mid', histtype='stepfilled') #ax4.plot( edges[:-1], bins, 'b-', drawstyle='steps-mid', ls='-' ) ax4.set_ylabel('count') ax4.set_xlabel('$m_{out}-m_{in}$') ax4.set_ylim(tuple(array(ax4.get_ylim()) * 1.2)) ax5 = fig.add_subplot(3, 2, 5) #ax5.plot( xin, dmag, 'bs',ls=' ') ax5.errorbar(xin, dmag, forced['magerr'], color='b', marker='s', ls=' ') ax5.set_ylabel('$m_{out}-m_{in}$') ax5.set_xlabel('$x_{in}$') ax5.axhline(0, color='0.3', lw=0.7) ax6 = fig.add_subplot(3, 2, 6) # ax6.plot( yin, dmag, 'bs',ls=' ') ax6.errorbar(yin, dmag, forced['magerr'], color='b', marker='s', ls=' ') ax6.set_ylabel('$m_{out}-m_{in}$') ax6.set_xlabel('$y_{in}$') ax6.axhline(0, color='0.3', lw=0.7) fig.suptitle("Fake SN Photometry for %s" % fakefilename) fig.subplots_adjust(left=0.12, right=0.95, bottom=0.08, top=0.95, wspace=0.32, hspace=0.2) savefig(outfilename) rcdefaults() return (dmag)
def plot_PieChart(self, selfExt, # **plotParams showTitle, titlePieChart, colorTitle, fontsizeTitle, # showLegend, # fontsizeLegend, showExplodedView, factorExplodeWedges, # colorChartBackground, fontsizeLabels, colorLabels ): ''' Calls pylab.plot to do the actual plotting; data is specified. Variables: self.plot_X_PieChart[] (x list of length 1) self.plot_Y_PieChart[] (y list of lists of variable length) ''' selfExt.MySQL_Output( 1, '** In PlotsForPylotMySQL in module_PylabPlotMySQL' ) # calculate min and max X values min_X = min(self.plot_X_PieChart) max_X = max(self.plot_X_PieChart) max_Y = max(self.plot_Y_PieChart) print ( '\nself.plot_X_PieChart = \n%s\n\nself.plot_Y_PieChart = \n%s\n\n' % (self.plot_X_PieChart,self.plot_Y_PieChart) ) lenYList = len(self.plot_Y_PieChart) # clear the figure # pylab.clf() # set defaults, before changes are made pylab.rcdefaults() # figure size widthChartFigure = 6.0 heightChartFigure = 6.0 # pylab.figure(2, figsize=(figWidth, figHeight)) pylab.figure( 2000, # facecolor='blue', facecolor='white', figsize=( float(widthChartFigure), float(heightChartFigure), ), ) pylab.clf() print( '\nlen(self.plot_Y_PieChart) =\n%d' % len(self.plot_Y_PieChart) ) print( '\nfactorExplodeWedges, type() =\n%s, %s' % (factorExplodeWedges, type(factorExplodeWedges)) ) # labels labels = [] icount=0 # labels = tuple(self.plot_X_PieChart) for label in self.plot_X_PieChart: labels.append( str(label) + '\n' + '(' + str(self.plot_Y_PieChart[icount]) + ')' ) icount += 1 print '\nlabels = \n',labels # rcParams # pylab.rcParams['axes.titlesize'] = fontsizeTitle # pylab.rcParams['axes.labelsize'] = fontsizeLabels # pylab.rcParams['axes.labelcolor'] = colorLabels fig_size = [widthChartFigure,heightChartFigure] params = { 'axes.titlesize' : fontsizeTitle, # for title # 'axes.labelsize' : fontsizeLabels, # 'axes.labelcolor' : colorLabels, # 'axes.facecolor' : colorChartBackground, 'figure.figsize' : fig_size, 'font.size' : int(fontsizeLabels), # for labels 'text.color' : colorLabels, # 'axes_left' : 0.1, # 'axes_bottom' : 0.1, # 'axes_height' : 0.9, # 'axes_width' : 0.9 } pylab.rcParams.update(params) # pylab.rcParams['legend.fontsize'] = 12.0 # title if showTitle: pylab.title( titlePieChart, color=colorTitle, size=fontsizeTitle ) # exploded view if showExplodedView: explode = tuple((len(self.plot_Y_PieChart))*[float(factorExplodeWedges)]) else: explode = None # compute percentages print '\nself.totalCount, type() = ',self.totalCount,type(self.totalCount) print 'self.plot_Y_PieChart, type[0] =',self.plot_Y_PieChart, type(self.plot_Y_PieChart[0]) # print '\nexplode = ',explode fractions = [float(yval)/float(self.totalCount)*100. for yval in self.plot_Y_PieChart] # print '\nfractions:\n',fractions # print '\nlabels:\n',labels # print '\nexplode:\n',explode # print '\ncolors:\n',self.plotOptions_Colors # ... plot pie chart pylab.pie( fractions, explode=explode, colors=self.plotOptions_Colors, labels=labels, autopct='%1.1f%%', shadow=True ) # force the display # pylab.show() try: pylab.show() except (ValueError): # except: errorParams = ( 'One of the input parameters for matplotlib\n' + ' is invalid. Check params.\n\n' + 'One possibility is that the user has specified\n' + ' a color that matplotlib does not recognize.\n\n' + 'Check all paramaters for validity and try again.\n\n' ) showinfo( 'Error: params', errorParams ) return
def twodhist(xs, ys, fname): import scipy xbins = scipy.arange(0, 1.5, 0.0225) ybins = scipy.arange(0, 1.5, 0.0225) prob_matrix, X, Y = scipy.histogram2d(ys, xs, bins=[xbins, ybins]) prob_matrix = prob_matrix / prob_matrix.max() import pylab #X, Y = pylab.meshgrid(zs_copy,zs_copy) print prob_matrix.shape, X.shape, Y.shape import pylab pylab.rcdefaults() params = { 'backend': 'ps', 'text.usetex': True, 'ps.usedistiller': 'xpdf', 'ps.distiller.res': 6000 } pylab.rcParams.update(params) fig_size = [8, 8] params = { 'axes.labelsize': 20, 'text.fontsize': 22, 'legend.fontsize': 22, 'xtick.labelsize': 20, 'ytick.labelsize': 20, 'scatter.s': 0.1, 'scatter.marker': 'o', 'figure.figsize': fig_size } pylab.rcParams.update(params) pylab.clf() print prob_matrix.max() prob_matrix[prob_matrix > 1] = 1. #pylab.axes([0.125,0.125,0.95-0.125,0.95-0.125]) #pylab.axes([0.125,0.25,0.95-0.125,0.95-0.25]) pylab.axes([0.125, 0.15, 0.95 - 0.125, 0.95 - 0.15]) #pylab.axes([0.225,0.15,0.95-0.225,0.95-0.15]) pylab.axis([0, 1.5, 0, 1.5]) pylab.pcolor(X, Y, -1. * prob_matrix, cmap='gray', alpha=0.9, shading='flat', edgecolors='None') pylab.axhline(y=1.2, color='black') pylab.plot(scipy.array([0, 2]), scipy.array([0, 2]), color='black') pylab.figtext(0.16, 0.89, 'HDFN', fontsize=20) pylab.xlabel('Spectroscopic z') pylab.ylabel('Photometric z') #pylab.plot([0,1],[0,1],color='red') #pylab.xlabel('SpecZ') #pylab.ylabel('PhotZ') pylab.savefig(fname) #,figsize=fig_size)
def _multi_bar_plot(self, title_lst, legend_lst, time_arr, error_lst, n_sim_lst): '''Plot the results if the code efficiency. ''' p.rcdefaults() fsize = 14 fig = p.figure(figsize=(15, 3)) rc('font', size=fsize) rc('legend', fontsize=fsize - 2) legend_lst = ['weave', 'cython', 'numpy'] # times are stored in 3d array - dimensions are: n_sampling, n_lang, n_run, n_times = time_arr.shape print 'arr', time_arr.shape times_sum = np.sum(time_arr, axis=n_times) p.subplots_adjust(left=0.1, right=0.95, wspace=0.1, bottom=0.15, top=0.8) for meth_i in range(n_sampling): ax1 = fig.add_subplot(1, n_sampling, meth_i + 1) ax1.set_xlabel('execution time [s]') ytick_pos = np.arange(n_lang) + 1 # ax1.axis([0, x_max_plt, 0, n_lang]) # todo: **2 n_vars if len(self.exact_arr) > 0: ax1.set_title( '%s: $ n_\mathrm{sim} = %s, \mathrm{e}_\mathrm{rms}=%s, \mathrm{e}_\mathrm{max}=%s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]), self._formatSciNotation('%.2e' % error_lst[meth_i][0]), self._formatSciNotation('%.2e' % error_lst[meth_i][1]))) else: ax1.set_title( '%s: $ n_\mathrm{sim} = %s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]))) ax1.set_yticks(ytick_pos) if meth_i == 0: ax1.set_yticklabels(legend_lst, fontsize=fsize + 2) else: ax1.set_yticklabels([]) ax1.set_xlim(0, 1.2 * np.max(times_sum[meth_i])) distance = 0.2 height = 1.0 / n_run - distance offset = height / 2.0 colors = ['w', 'w', 'w', 'r', 'y', 'b', 'g', 'm'] hatches = ['/', '\\', 'x', '-', '+', '|', 'o', 'O', '.', '*'] label_lst = ['sampling', 'compilation', 'integration'] for i in range(n_run): pos = np.arange(n_lang) + 1 - offset + i * height end_bar_pos = np.zeros((n_lang, ), dtype='d') for j in range(n_times): if i > 0: label = label_lst[j] else: label = None bar_lengths = time_arr[meth_i, :, i, j] rects = ax1.barh(pos, bar_lengths, align='center', height=height, left=end_bar_pos, color=colors[j], edgecolor='k', hatch=hatches[j], label=label) end_bar_pos += bar_lengths for k in range(n_lang): x_val = times_sum[meth_i, k, i] + 0.01 * np.max(times_sum[meth_i]) ax1.text(x_val, pos[k], '$%4.2f\,$s' % x_val, horizontalalignment='left', verticalalignment='center', color='black') #, weight = 'bold') if meth_i == 0: ax1.text(0.02 * np.max(times_sum[0]), pos[k], '$%i.$' % (i + 1), horizontalalignment='left', verticalalignment='center', color='black', bbox=dict(pad=0., ec="w", fc="w")) p.legend(loc=0)
def fakephot( fakefilename, outfilename=None ): """ collect photometry for all fakes in the image, make plots of input vs output positions and mags """ import os fakeroot = os.path.splitext(os.path.basename( fakefilename ))[0] from pylab import rcParams, rcdefaults from math import sqrt rcParams['lines.linewidth']=1.5 rcParams['font.size']=15 # text big enough for a half-page fig rcParams['axes.labelsize'] = 15 # fontsize of the x and y labels if outfilename==None : outfilename = fakefilename.replace('.fits', '_fakephot.pdf') # construct coord and mag lists from the fits header keywords coordlist,xin,yin,magin = [],[],[],[] hdr = pyfits.getheader( fakefilename ) for key in hdr.keys() : if (key.startswith('FAKE') and key.endswith('X') ): xin.append(hdr[key]) if (key.startswith('FAKE') and key.endswith('Y') ): yin.append(hdr[key]) if (key.startswith('FAKE') and key.endswith('M') ): magin.append(hdr[key]) for i in range(len(xin)): coordlist.append((xin[i],yin[i])) # collect forced photometry at fixed positions (for checking mags) forced = run( fakefilename, coordlist, WCS=False, outroot=fakeroot+'_forced', calgorithm='none',poisson=True, smallskyann=False ) # collect photometry with recentering allowed (for checking positions) free = run( fakefilename, coordlist, WCS=False, outroot=fakeroot+'_free',poisson=True, smallskyann=False ) # compute residuals dx = free['x']-xin dy = free['y']-yin dmag = forced['mag'] - magin dmag = nan_to_num( dmag ) # make some plots from matplotlib.pyplot import figure, clf, savefig, autoscale # autoscale( enable=True, axis='both', tight=False ) fig = figure(1, figsize=[8.5,11]) ax1 = fig.add_subplot(3,2,1) ax1.plot( xin, dx, 'ro', ls=' ' ) ax1.set_ylabel('$x_{out}-x_{in}$') ax1.set_xlabel('$x_{in}$') ax1.axhline(0, color='0.3', lw=0.7 ) ax2 = fig.add_subplot(3,2,2) ax2.plot( yin, dy, 'ro', ls=' ' ) ax2.set_ylabel('$y_{out}-y_{in}$') ax2.set_xlabel('$y_{in}$') ax2.axhline(0, color='0.3', lw=0.7 ) ax3 = fig.add_subplot(3,2,3) ax3.plot( magin, forced['mag'], 'bs', ls=' ' ) ax3.plot( [ max(magin), min(magin)], [ max(magin), min(magin)], 'k-' ) ax3.errorbar( magin, forced['mag'], forced['magerr'], marker='s', color='b', ls=' ' ) ax3.set_ylabel('$m_{out}$') ax3.set_xlabel('$m_{in}$') #bins,edges = histogram( dmag, bins=max(10, len(dmag)/10) ) ax4 = fig.add_subplot(3,2,4) histout = ax4.hist( dmag, bins=max(5,sqrt(len(magin))), align='mid',histtype='stepfilled' ) #ax4.plot( edges[:-1], bins, 'b-', drawstyle='steps-mid', ls='-' ) ax4.set_ylabel('count') ax4.set_xlabel('$m_{out}-m_{in}$') ax4.set_ylim( tuple(array(ax4.get_ylim())*1.2) ) ax5 = fig.add_subplot(3,2,5) #ax5.plot( xin, dmag, 'bs',ls=' ') ax5.errorbar( xin, dmag, forced['magerr'], color='b',marker='s',ls=' ') ax5.set_ylabel('$m_{out}-m_{in}$') ax5.set_xlabel('$x_{in}$') ax5.axhline(0, color='0.3', lw=0.7 ) ax6 = fig.add_subplot(3,2,6) # ax6.plot( yin, dmag, 'bs',ls=' ') ax6.errorbar( yin, dmag, forced['magerr'], color='b',marker='s',ls=' ') ax6.set_ylabel('$m_{out}-m_{in}$') ax6.set_xlabel('$y_{in}$') ax6.axhline(0, color='0.3', lw=0.7 ) fig.suptitle("Fake SN Photometry for %s"%fakefilename) fig.subplots_adjust( left=0.12, right=0.95, bottom=0.08, top=0.95, wspace=0.32, hspace=0.2 ) savefig(outfilename) rcdefaults() return( dmag )
def plot_BarChart(self, selfExt, # **plotParams showTitle, showYLabel, showGrid, useLogScale, orientBarsHorizontal, titleBarChart, labelYBarChart, fontsizeChartTitle, fontsizeChartLabels, fontsizeGeneral, fontsizeXTickLabels, fontsizeYTickLabels, fontsizeLegend, colorChartTitle, colorChartBackground, colorChartBorder, colorChartLabels, colorXTickLabels, colorYTickLabels, widthChartFigure, heightChartFigure, widthBars, widthBarsEdge, colorBars, colorBarsEdge, alignBars, axesLeft, axesBottom, axesWidth, axesHeight ): ''' Calls pylab.plot to do the actual plotting; data is specified. Variables: self.plot_X_BarChart[] (x list of length 1) self.plot_Y_BarChart[] (y list of lists of variable length) ''' selfExt.MySQL_Output( 1, '** In PlotsForPylotMySQL in module_PylabPlotMySQL' ) # DWB Delete this print print '1. showTitle =',showTitle print '2. showYLabel =',showYLabel print '3. showGrid =',showGrid print '4. useLogScale =',useLogScale print '5. orientBarsHorizontal =',orientBarsHorizontal print '6. titleBarChart =',titleBarChart print '7. labelYBarChart =',labelYBarChart print '8. fontsizeChartTitle =',fontsizeChartTitle print '9. fontsizeChartLabels =',fontsizeChartLabels print '10. fontsizeGeneral =',fontsizeGeneral print '11. fontsizeXTickLabels =',fontsizeXTickLabels print '12. fontsizeYTickLabels =',fontsizeYTickLabels print '13. fontsizeLegend =',fontsizeLegend print '14. colorChartTitle =',colorChartTitle print '15. colorChartBackground =',colorChartBackground print '16. colorChartBorder =',colorChartBorder print '17. colorChartLabels =',colorChartLabels print '18. colorXTickLabels =',colorXTickLabels print '19. colorYTickLabels =',colorYTickLabels print '20. widthChartFigure =',widthChartFigure print '21. heightChartFigure =',heightChartFigure print '22. widthBars =',widthBars print '23. widthBarsEdge =',widthBarsEdge print '24. colorBars =',colorBars print '25. colorBarsEdge =',colorBarsEdge print '26. alignBars =',alignBars print '27. axesLeft =',axesLeft print '28. axesBottom =',axesBottom print '29. axesWidth =',axesWidth print '30. axesHeight =',axesHeight # --- end of delete --- # calculate min and max X values min_X = min(self.plot_X_BarChart) max_X = max(self.plot_X_BarChart) max_Y = max(self.plot_Y_BarChart) print ( '\nself.plot_X_BarChart = \n%s\n\nself.plot_Y_BarChart = \n%s\n\n' % (self.plot_X_BarChart,self.plot_Y_BarChart) ) lenYList = len(self.plot_Y_BarChart) lenXList = len(self.plot_X_BarChart) # x index index_X = numpy.arange(len(self.plot_X_BarChart)) print '\nindex_X from numpy.arange:\n',index_X print print 'colorChartBorder, type() = ',colorChartBorder,type(colorChartBorder) # set defaults, before changes are made pylab.rcdefaults() # tell pylab which figure we are dealing with; otherwise, defaults to Figure 1, which conflicts with regular x-y plots pylab.figure( 1000, facecolor=colorChartBorder, # does NOT work (must be a bug in matplotlib) # facecolor='white', figsize=( float(widthChartFigure), float(heightChartFigure) ), ) # clear the figure pylab.clf() # rcParams params = { 'font.size' : fontsizeGeneral, 'axes.facecolor' : colorChartBackground, # 'figure.figsize' : [float(widthChartFigure), float(heightChartFigure)], 'axes.titlesize' : fontsizeChartTitle, 'axes.labelsize' : fontsizeChartLabels, 'axes.labelcolor' : colorChartLabels, 'xtick.labelsize' : fontsizeXTickLabels, 'xtick.color' : colorXTickLabels, 'ytick.labelsize' : fontsizeYTickLabels, 'ytick.color' : colorYTickLabels, } # update the params pylab.rcParams.update(params) # form bars pylab.bar( index_X, self.plot_Y_BarChart, width=float(widthBars), color=colorBars, edgecolor=colorBarsEdge, linewidth=float(widthBarsEdge), # xerr=None, # yerr=None, # ecolor=None, # capsize=3, # align=alignBars, # orientation=orient, # log=useLogScale ) # ... show grid pylab.grid(showGrid) # ... convert x titles to numbers ''' xrange=[] for i in range(len(self.plot_X_BarChart)): xrange.append(i) print '\nxrange =\n',xrange ''' # ... horizontal or vertical bars if orientBarsHorizontal: orient = 'horizontal' else: orient = 'vertical' orient = 'vertical' # ... logscale if useLogScale: logScale = True else: logScale = False logScale = False # in case labels are long, put a <CR> in every other label # ... make strings out of every label plot_X_BarChart_Labels=[] if orient <> 'horizontal': # orient == 'vertical' for i in range(len(self.plot_X_BarChart)): if i%2 == 1: # odd plot_X_BarChart_Labels.append('\n\n' + str(self.plot_X_BarChart[i])) else: # even plot_X_BarChart_Labels.append(str(self.plot_X_BarChart[i])) # labels and numbers for tick marks pylab.xticks(index_X + float(widthBars)/2., plot_X_BarChart_Labels) values_Y = numpy.arange(0,math.ceil(1.05*max_Y)+1) pylab.yticks(values_Y) else: # orient == 'horizontal': for i in range(len(self.plot_X_BarChart)): if i%2 == 1: # odd plot_X_BarChart_Labels.append(' ' + str(self.plot_X_BarChart[i])) else: # even plot_X_BarChart_Labels.append(str(self.plot_X_BarChart[i])) # title if showTitle: pylab.title( titleBarChart, color=colorChartTitle, size=fontsizeChartTitle ) # y label if showYLabel: pylab.ylabel(labelYBarChart) # force the display # pylab.show() # ''' try: pylab.show() except (ValueError): # except: errorParams = ( 'One of the input parameters for matplotlib\n' + ' is invalid. Check params.\n\n' + 'One possibility is that the user has specified\n' + ' a color that matplotlib does not recognize.\n\n' + 'Check all paramaters for validity and try again.\n\n' ) showinfo( 'Error: params', errorParams ) return
def plot_OnePlotPerCurve(self, showMainTitle, showPlotTitles, showGrids, mainTitle, colorMainTitle, fontsizeMainTitle, fontsizePlotTitles, fontsizeXYLabels, colorXYLabels, fontsizeXTicks, colorXTicks, fontsizeYTicks, colorYTicks, colorChartBackground, colorPlotBorder, plotStyle, plotBaseX, plotBaseY, lineWidth, markerSize, ): ''' Calls pylab.plot to do the actual plotting; data is specified. Max number of plots: 25 Variables: self.plot_X[] (x list of length 1) self.plot_Y[] (y list of lists of variable length) Plot Options: self.plotOptions (list of third argument plot line colors, line styles, line markers) plotOptions_SubPlot (number determining rows x columns x plot_number) Labels: x label: self.varLabelX y label: self.varLabelY[] plot title: self.varPlotTitle ''' if DEBUG: print('\n-- DEBUG --') print('showMainTitle: %s (%s)' % (showMainTitle, type(showMainTitle))) print('showPlotTitles: %s (%s)' % (showPlotTitles,type(showPlotTitles))) print('showGrids: %s (%s)' % (showGrids,type(showGrids))) print('mainTitle: %s (%s)' % (mainTitle,type(mainTitle))) print('fontsizeMainTitle: %s (%s)' % (fontsizeMainTitle,type(fontsizeMainTitle))) print('fontsizePlotTitles: %s (%s)' % (fontsizePlotTitles,type(fontsizePlotTitles))) print('fontsizeXYLabels: %s (%s)' % (fontsizeXYLabels,type(fontsizeXYLabels))) print('colorXYLabels: %s (%s)' % (colorXYLabels,type(colorXYLabels))) print('fontsizeXTicks: %s (%s)' % (fontsizeXTicks,type(fontsizeXTicks))) print('colorXTicks: %s (%s)' % (colorXTicks,type(colorXTicks))) print('fontsizeYTicks: %s (%s)' % (fontsizeYTicks,type(fontsizeYTicks))) print('colorYTicks: %s (%s)' % (colorYTicks,type(colorYTicks))) print('colorChartBackground: %s (%s)' % (colorChartBackground,type(colorChartBackground))) print('plotStyle: %s (%s)' % (plotStyle,type(plotStyle))) print('plotBaseX: %s (%s)' % (plotBaseX,type(plotBaseX))) print('plotBaseY: %s (%s)' % (plotBaseY,type(plotBaseY))) print('lineWidth: %s (%s)' % (lineWidth,type(lineWidth))) print('markerSize: %s (%s)' % (markerSize,type(markerSize))) print('-- END OF DEBUG --\n') # destroy old popup # try: # self.frame_ToplevelPylabPlotMySQL.destroy() # except: # pass # determine dimension of subplot, upto 'numberCurvesMax' plots max lenYList = len(self.plot_Y) # tells how many curves, and therefore how many plots, are to be drawn # bounds check; no more than 'numberCurvesMax' plots in a 5x5 array allowed; if lenYList > numberCurvesMax: stringLenYList = ( 'Number of plots out of range:\n\n' + ' Number of plots attempted: ' + str(lenYList) + '\n' + ' Max number of plots allowed: ' + str(numberCurvesMax) + '\n\n' + 'To continue with plotting the first ' + str(numberCurvesMax) + '\n' + ' of ' + str(lenYList) + ' plots selected, click "OK".' + '\n\n' + 'To halt plotting, click "CANCEL".' + '\n' ) ans = askokcancel( 'Max number of plots exceeded', stringLenYList ) if not ans: return else: lenYList = numberCurvesMax plotOptions_SubPlot = [] if lenYList == 1: plotOptions_SubPlot = [1,1,0] elif lenYList <= 2: plotOptions_SubPlot = [2,1,0] elif lenYList <= 4: plotOptions_SubPlot = [2,2,0] elif lenYList <= 6: plotOptions_SubPlot = [3,2,0] elif lenYList <= 9: plotOptions_SubPlot = [3,3,0] elif lenYList <= 12: plotOptions_SubPlot = [4,3,0] elif lenYList <= 16: plotOptions_SubPlot = [4,4,0] elif lenYList <= 20: plotOptions_SubPlot = [5,4,0] elif lenYList <= 25: plotOptions_SubPlot = [5,5,0] else: stringLenYList = ( 'Number of plots out of range:\n' + ' Number of plots attempted: ' + str(lenYList) + '\n' + ' Max number of plots allowed: ' + str(lenYList_Max) + '\n\n' + 'Please choose 25 or less plots and try again.\n' ) print stringLenYList self.MySQL_Output( 1, stringLenYList ) showinfo( 'Error: too many plots', '\n' + stringLenYList + '\n' ) return # reset defaults pylab.rcdefaults() # tell pylab which figue we are dealing with; otherwise, defaults to Figure 1 pylab.figure( self.numberPylabPlotFigure, facecolor=colorPlotBorder ) # color plot border # pylab.figure().patch.set_facecolor(colorPlotBorder) # clear the figure if not self.keepPreviousPlot: pylab.clf() # set some plot params params = { # 'font.size' : int(fontsizePlotTitles), #fontsizeGeneral for title 'axes.facecolor' : colorChartBackground, #chart background color 'axes.labelsize' : int(fontsizeXYLabels), #fontsizeChartLabels, 'axes.labelcolor' : colorXYLabels, #chart x-y label colors 'xtick.labelsize' : int(fontsizeXTicks), #fontsizeXTickLabels, 'xtick.color' : colorXTicks, #colorXTickLabels, 'ytick.labelsize' : int(fontsizeYTicks), #fontsizeYTickLabels, 'ytick.color' : colorYTicks, #colorYTickLabels, # 'lines.linewidth' : lineWidth, # width of data plot lines (0=thin, 5=thick) } # update the params pylab.rcParams.update(params) # create plots # ... subplot base number, which determines plot layout in plot window numRowsTotal = plotOptions_SubPlot[0] numColumnsTotal = plotOptions_SubPlot[1] subplot = 0 # iterate over plots for numberPlot in range(lenYList): # keep track of subplot number subplot+=1 # define subplot FIRST before defining other parameters self.pylabSubplot = pylab.subplot(numRowsTotal,numColumnsTotal,subplot) # set plot sizes within frame; also set distance from each other vertically and horizontally pylab.subplots_adjust( left=0.125, right=0.9, bottom=0.1, top=0.9, wspace=0.30, hspace=0.5, ) pylab.grid(showGrids) # use following x and y label for multiplot labeling # ... x label try: pylab.xlabel(self.label_X[numberPlot]) except: stringErrorXLabel = ( 'The value\n\n' + ' self.label_X[numberPlot]\n\n' + 'is out of range in module_PylabPlotMySQL_Single.\n\n' + 'This is a coding error. Please contact the\n' + 'code administrator.' ) print stringErrorXLabel showinfo( 'Error: out of range', stringErrorXLabel ) return # ... y label try: pylab.ylabel(self.label_Y[numberPlot]) except: stringErrorYLabel = ( 'The value\n\n' + ' self.label_Y[numberPlot]\n\n' + 'is out of range in module_PylabPlotMySQL_Single.\n\n' + 'This is a coding error. Please contact the\n' + 'code administrator.' ) print stringErrorYLabel showinfo( 'Error: out of range', stringErrorYLabel ) return # ... use title for single plots only # pylab.title(self.varPlotTitle.get()) if showPlotTitles: colorTitle = 'black' pylab.title( self.label_Y[numberPlot], color=colorTitle, size=fontsizePlotTitles ) if DEBUG: print('self.plotOptions[0]: %s',self.plotOptions[0]) # self.plotStyleForCurve( module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, self.plot_X[numberPlot], self.plot_Y[numberPlot], self.plotOptions[0], lineWidth, markerSize, plotBaseX, plotBaseY, ) # zero out global values for xMin, yMin, xMax, yMax for each plot self.xMin_Global = [] self.xMax_Global = [] self.yMin_Global = [] self.yMax_Global = [] # determine min and max values for each plot # self.globalMinMaxValues( module_PlotUtilities.globalMinMaxValues( self, self.plot_X[numberPlot], self.plot_Y[numberPlot] ) # change labels to 'e' if needed if plotStyle == 'semilogx' or plotStyle == 'loglog': if plotBaseX == 'e': xMin_Local = min(self.xMin_Global) xMax_Local = max(self.xMax_Global) # self.formNewXLabels(xMin_Local,xMax_Local,colorXTicks,fontsizeXTicks) okXLabels = module_PlotUtilities.formNewXLabels( self,pylab,xMin_Local,xMax_Local,colorXTicks,fontsizeXTicks ) if not okXLabels: return if plotStyle == 'semilogy' or plotStyle == 'loglog': if plotBaseY == 'e': yMin_Local = min(self.yMin_Global) yMax_Local = max(self.yMax_Global) # self.formNewYLabels(yMin_Local,yMax_Local,colorYTicks,fontsizeYTicks) okYLabels = module_PlotUtilities.formNewYLabels( self,pylab,yMin_Local,yMax_Local,colorYTicks,fontsizeYTicks ) if not okYLabels: return # --- end of for loop --- # show overall plot title if showMainTitle: pylab.suptitle( mainTitle, color=colorMainTitle, fontsize=fontsizeMainTitle ) # graph the plot pylab.show() return
def __init__( self, selfExternal, parent, keepPreviousPlot, xwin, ywin, colorbg, xxDataLists, yyDataLists, numberOfTableCurves, numberOfBufferCurves, numberPylabPlotFigure, # **kwargs showTitle, showYLabel, showXLabel, showLegend, showLegendShadow, showGrid, showReferenceCurve, showSlopedStraightLineReferenceCurve, showHorizontalStraightLineReferenceCurve, showVerticalStraightLineReferenceCurve, colorBackground, colorXYLabels, colorXTicks, colorYTicks, colorTitle, colorPlotBorder, fontsizeTitle, fontsizeXYLabels, fontsizeXTicks, fontsizeYTicks, fontsizeLegend, valueTitle, valueLabelY, valueLabelX, valueLegendLocation, valuesLegendLabels, valueRefCurveMultiplier, valueRefCurveLabel, valueSlopedStraightLineRefCurveLabel, valueHorizontalStraightLineRefCurveLabel, valueVerticalStraightLineRefCurveLabel, valuesRefCurvePlotYList, valuesRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList, valuesSlopedStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList, valuesHorizontalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList, valuesVerticalStraightLineRefCurvePlotXList, plotStyle, plotBaseX, plotBaseY, lineWidthCurveFit, numPointsForCurveFit, markerSize, connectDataPoints, polyDegree, plotPolyDegree, plotAllLesserDegrees, numberDecimalPlacesInEqn, # 0 for integers; otherwise, range is 1 to 10, editable formatPolyCoefs, ): selfExternal.MySQL_Output( 1, '\n** In class ScatterPlot in module_PylabPlotMySQL_ScatterPlot' ) if DEBUG: print('\nHorizontal xlist:') print(valuesHorizontalStraightLineRefCurvePlotXList) print('\nHorizontal ylist:') print(valuesHorizontalStraightLineRefCurvePlotYList) # reset defaults pylab.rcdefaults() # tell pylab which figue we are dealing with; otherwise, defaults to Figure 1, which conflicts with regular x-y plots pylab.figure( numberPylabPlotFigure, facecolor=colorPlotBorder ) # color plot border # pylab.figure().patch.set_facecolor(colorPlotBorder) # clear the figure if not keepPreviousPlot: pylab.clf() # set plot background color matplotlib.rc('axes', facecolor = colorBackground) matplotlib.rc('axes', labelsize = int(fontsizeXYLabels)) matplotlib.rc('axes', labelcolor = colorXYLabels) matplotlib.rc('xtick', labelsize = int(fontsizeXTicks)) matplotlib.rc('xtick', color = colorXTicks) matplotlib.rc('ytick', labelsize = int(fontsizeYTicks)) matplotlib.rc('ytick', color = colorYTicks) # scatter plot plotting options (4 colors, 4 line styles, and 7 markers = 112 unique plot possibilities); # however, since line styles are not used with scatterplots, there are 28 unique plot possibilities # ... colors: b = blue, g = green, k = black, m = magenta # ... NOTE: Don't use red here; red is used for polynomial curve fits plotOptions_Colors = ['b','g','k','m',] # ... line style: '-' solid line, '--' dashed line, ':' dotted line, '-.' dash-dot line # ... NOTE: these are not used for data plotted with scatterplots! plotOptions_LineStyles = ['-','--',':','-.'] plotOptions_LineStyles = ['--'] # ... markers: s = square, o = filled circle, d = diamond, v = down triangle, # ^ = up triangle, < = triangle left, > triangle right plotOptions_Markers = ['s','o','d','v','^','<','>'] # curve fit plotting options # ... colors: r = red curveFitOptions_Colors = ['r'] # ... line style: '-' solid line, '--' dashed line, ':' dotted line, '-.' dash-dot line curveFitOptions_LineStyles = ['-','--',':','-.'] # markers: s = square, o = filled circle, d = diamond, v = down triangle, # ^ = up triangle, < = triangle left, > triangle right # NOTE: do not use markers for curve fits, just use solid lines, dashed lines, etc. curveFitOptions_Markers = ['s','o','d','v','^','<','>'] # form list of plot options for data plotOptions = [] if connectDataPoints: for style in plotOptions_LineStyles: for color in plotOptions_Colors: for marker in plotOptions_Markers: plotOptions.append(color + style + marker) else: for color in plotOptions_Colors: for marker in plotOptions_Markers: plotOptions.append(color + marker) # determine total number of options, so that when plotting, we can cycle thru the option using modulo function plotOptions_Total = len(plotOptions) # form list of plot options for curve fit curveFitOptions = [] for style in curveFitOptions_LineStyles: for color in curveFitOptions_Colors: # for marker in curveFitOptions_Markers: curveFitOptions.append(color + style) # curveFitOptions.append(color + style + marker) # determine total number of options so that when plotting we can cycle thru the option using modulo funtion curveFitOptions_Total = len(curveFitOptions) if DEBUG: print('plotOptions = \n%s\n' % plotOptions) print('curveFitOptions = \n%s\n' % curveFitOptions) # create plots # ... only one plot subplot=111 self.pylabSubplot = pylab.subplot(subplot) if DEBUG: print('\nxxDataLists from calling program:') print(xxDataLists) print('\nyyDataLists from calling program:') print(yyDataLists) print('') # keep track of global values for xMin, yMin, xMax, yMax self.xMin_Global = [] self.xMax_Global = [] self.yMin_Global = [] self.yMax_Global = [] # plot data; each list of data is plotted with separate markers for numberPlot in range(len(yyDataLists)): # plot based on plotStyle plotOptionsIndex = numberPlot%plotOptions_Total module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, xxDataLists[numberPlot], yyDataLists[numberPlot], plotOptions[plotOptionsIndex], lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, xxDataLists[numberPlot], yyDataLists[numberPlot] ) # compute 1-D vectors for both x and y by joining all data together # ... used for determining polynomial coefficients by calling pylab.polyfit() x = [] y = [] for i in range(len(xxDataLists)): x.extend(xxDataLists[i]) y.extend(yyDataLists[i]) # print('\n x scatter = %s' % x) # print('\n y scatter = %s' % y) # find min and max values for both x and y xmax = max(x) xmin = min(x) # ... 'bestX' values for later determining 'bestY' deltaX = (xmax - xmin)/float(numPointsForCurveFit) bestX = [] for i in range(numPointsForCurveFit + 1): if i == 0: xtemp = xmin else: xtemp += deltaX bestX.append(xtemp) if DEBUG: print('\nx = %s\n' % x) print('\ny = %s\n' % y) print('\nlen(x) = %s\n' % len(x)) print('\nlen(y) = %s\n' % len(y)) print('\nxmin = %s\n' % xmin) print('\nxmax = %s\n' % xmax) print('\nbestX = %s\n' % bestX) # determine bestY best fit for bestX; # ... also, string for polynomial equation to be listed in legend bestY, stringEqn, stringEqnForLegend = \ self.dataFit(x,y,bestX,polyDegree,numberDecimalPlacesInEqn,formatPolyCoefs) # ... parameters stored for use in calling program to place in storage buffer # ... initialization selfExternal.curvefit_CurveFitEquations_Scatter = [] selfExternal.curvefit_BestY_Scatter = [] selfExternal.curvefit_YHeader_Scatter = [] # ... define values for main curve fit equation selfExternal.curvefit_CurveFitEquations_Scatter.append(stringEqnForLegend.lstrip()) selfExternal.curvefit_BestY_Scatter.append(bestY) selfExternal.curvefit_BestX_Scatter = bestX # selfExternal.curvefit_YHeader_Scatter.append(valueLabelY) selfExternal.curvefit_YHeader_Scatter.append(stringEqnForLegend.lstrip()) selfExternal.curvefit_XHeader_Scatter = valueLabelX selfExternal.curvefit_Title_Scatter = valueTitle if DEBUG: print('\ncurveFitOptions = \n') print(curveFitOptions) print() # plot polynomial curve fit if plotPolyDegree: valuesLegendLabels.append(stringEqnForLegend) module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, bestX, bestY, curveFitOptions[0], lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues(self,bestX,bestY) # fit all lesser degrees if (plotAllLesserDegrees) and (polyDegree > 1): optionsIndex = 0 for i in range(polyDegree - 1,0,-1): bestY, stringEqn, stringEqnForLegend = \ self.dataFit(x,y,bestX,i,numberDecimalPlacesInEqn,formatPolyCoefs) if DEBUG: print('For polynomial of degree %s: %s' % (i,stringEqn)) # ... store for use in calling program; strip leading white space selfExternal.curvefit_CurveFitEquations_Scatter.append(stringEqnForLegend.lstrip()) selfExternal.curvefit_BestY_Scatter.append(bestY) selfExternal.curvefit_YHeader_Scatter.append(stringEqnForLegend.lstrip()) # ... define options index optionsIndex += 1 # ... cycle thru the values using the modulo operator curveFitOptionsIndex = optionsIndex%curveFitOptions_Total valuesLegendLabels.append(stringEqnForLegend) module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, bestX, bestY, curveFitOptions[curveFitOptionsIndex], lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues(self,bestX,bestY) # reference plot, if desired if showReferenceCurve: valuesLegendLabels.append( str(valueRefCurveMultiplier) + ' * (' + valueRefCurveLabel + ') [ref]' ) stringInvalidMultiplier = ( 'Unable to plot reference curve:' + '\n' ' Invalid value for reference curve multiplier.\n' + ' Multiplier must be a string representing either\n' + ' an integer, float, or fraction (e.g., 1/5).\n' ) # change multiplier to decimal tempMult = valueRefCurveMultiplier if tempMult == '1/10': multiplier = 1./10. elif tempMult == '1/9': multiplier = 1./9. elif tempMult == '1/8': multiplier = 1./8. elif tempMult == '1/7': multiplier = 1./7. elif tempMult == '1/6': multiplier = 1./6. elif tempMult == '1/5': multiplier = 1./5. elif tempMult == '1/4': multiplier = 1./4. elif tempMult == '1/3': multiplier = 1./3. elif tempMult == '1/2': multiplier = 1./2. elif tempMult == '2': multiplier = 2. elif tempMult == '3': multiplier = 3. elif tempMult == '4': multiplier = 4. elif tempMult == '5': multiplier = 5. elif tempMult == '6': multiplier = 6. elif tempMult == '7': multiplier = 7. elif tempMult == '8': multiplier = 8. elif tempMult == '9': multiplier = 9. elif tempMult == '10': multiplier = 10. elif tempMult.count('/') == 1: # just one division sign is present in string, so try arbitrary fraction; if fails, nothing left to try tempMult_New = tempMult.split('/') try: multiplier = float(tempMult_New[0]) / float(tempMult_New[1]) except: # form error string selfExt.MySQL_Output( 1, stringInvalidMultiplier ) showinfo( 'Error: invalid value', '\n' + stringInvalidMultiplier + '\n' ) return else: # last ditch chance to just float the string representing a number; if fails, nothing left to try try: multiplier = float(valueRefCurveMultiplier) except: selfExt.MySQL_Output( 1, stringInvalidMultiplier ) showinfo( 'Error: invalid value', '\n' + stringInvalidMultiplier + '\n' ) return # choose correct X-values for reference curve # ... plot X and Y lists plot_X_RefCurve = valuesRefCurvePlotXList plot_Y_RefCurve = [float(y)*float(multiplier) for y in valuesRefCurvePlotYList] # ... set up plots module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, plot_X_RefCurve, plot_Y_RefCurve, 'r--d', lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, plot_X_RefCurve, plot_Y_RefCurve ) # sloped straight-line reference curve, if desired if showSlopedStraightLineReferenceCurve: valuesLegendLabels.append( valueSlopedStraightLineRefCurveLabel ) # ... no need to error check; validation done in "SCATTER PLOT SPECS" window module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesSlopedStraightLineRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList, 'r--s', lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesSlopedStraightLineRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList ) # horizontal straight-line reference curve, if desired if showHorizontalStraightLineReferenceCurve: valuesLegendLabels.append( valueHorizontalStraightLineRefCurveLabel ) # ... no need to error check; validation done in "SCATTER PLOT SPECS" window module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesHorizontalStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList, 'r--s', lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesHorizontalStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList ) # vertical straight-line reference curve, if desired if showVerticalStraightLineReferenceCurve: valuesLegendLabels.append( valueVerticalStraightLineRefCurveLabel ) # ... no need to error check; validation done in "SCATTER PLOT SPECS" window module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesVerticalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList, 'r--s', lineWidthCurveFit, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesVerticalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList ) # display legend if showLegend: if DEBUG: print '\n====\nvaluesLegendLabels:\n',valuesLegendLabels # legend labels stringLegendLabels = [] # lenLabels = len(self.plot_Labels) lenLabels = len(valuesLegendLabels) # for label in self.plot_Labels: for label in valuesLegendLabels: stringLegendLabels.append(label) # title (fontsize specified in rcparams) if showTitle: pylab.title( valueTitle, color=colorTitle, size=fontsizeTitle, ) # y label (fontsize specified in rcparams) if showYLabel: pylab.ylabel( valueLabelY, color=colorXYLabels, size=fontsizeXYLabels, ) # x label (fontsize specified in rcparams) if showXLabel: pylab.xlabel( valueLabelX, color=colorXYLabels, size=fontsizeXYLabels, ) # legend if showLegend: pylab.legend( stringLegendLabels, prop={'size':fontsizeLegend}, loc=valueLegendLocation, shadow=showLegendShadow, ) # if any plots have base 'e', form new labels; # ... pass in all min-max data if DEBUG: print('\nself.xMin_Global:') print(self.xMin_Global) print('\nself.xMax_Global:') print(self.xMax_Global) print('\nself.yMin_Global:') print(self.yMin_Global) print('\nself.yMax_Global:') print(self.yMax_Global) print('') if plotStyle == 'semilogx' or plotStyle == 'loglog': if plotBaseX == 'e': xMin_Local = min(self.xMin_Global) xMax_Local = max(self.xMax_Global) okXLabels = module_PlotUtilities.formNewXLabels( self,pylab,xMin_Local,xMax_Local,colorXTicks,fontsizeXTicks ) if not okXLabels: return if plotStyle == 'semilogy' or plotStyle == 'loglog': if plotBaseY == 'e': yMin_Local = min(self.yMin_Global) yMax_Local = max(self.yMax_Global) okYLabels = module_PlotUtilities.formNewYLabels( self,pylab,yMin_Local,yMax_Local,colorYTicks,fontsizeYTicks ) if not okYLabels: return # grid if showGrid: pylab.grid(showGrid) # finally, plot it pylab.show() return
def plot_ensemble_traj(m, ens, sampling_freq=10, fontSizeLabels=24, fontSizeLegend=20,rescale=1.,paper_fig=False): """ this function plots the range of ensemble predictions for a SloppyScaling Model class, to speed up the calculation, one can specify the sampling frequency of the ensemble if the ensemble was sampled at a lower temperature than desired, one can set a rescale factor "rescale = T_H/T_L" """ if paper_fig: fig_width_pt = 246.0 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0/72.27 # Convert pt to inch golden_mean = (scipy.sqrt(5)-1.0)/2.0 # Aesthetic ratio fig_width = fig_width_pt*inches_per_pt # width in inches fig_height = fig_width*golden_mean # height in inches fig_size = [fig_width,fig_height] pylab.rcdefaults() params = {'axes.labelsize': 10,\ 'text.fontsize': 10,\ 'legend.fontsize': 8,\ 'xtick.labelsize': 10,\ 'ytick.labelsize': 10,\ 'lines.markersize':3, 'text.usetex': True,\ 'figure.figsize': fig_size} pylab.rcParams.update(params) font = {'family':'serif', 'serif':'Times New Roman'} pylab.rc('font',**font) else: pylab.rcdefaults() pylab.rcParams.update({'backend':'ps', 'xtick.labelsize':24, 'xtick.major.size':20, 'xtick.minor.size':10, 'ytick.labelsize':24, 'ytick.major.size':20, 'ytick.minor.size':10, 'lines.markersize':10, 'axes.labelsize':24,\ 'legend.fontsize':20, 'legend.columnspacing':1.5, 'figure.figsize':[10.,10.],\ 'text.usetex':False, }) font = {'family':'serif', 'serif':'Times New Roman'} pylab.rc('font',**font) num_to_count = int(len(ens)/sampling_freq) # plot trajectories # want to calculate the mean of the ensemble and also the range of the ensemble... (use pylab.fill to plot) # but you can't do this by calculating mean of params, you have to do this by calculating mean of points along trajectory!!!!!!! # for using jointModules pylab.ioff() ax0 = [1.e99,0,1.e99,0] for model in m.Models.values(): pylab.figure() #pylab.axes([0.2,0.2,0.95-0.2,0.95-0.20]) #pylab.axes([0.125,0.10,0.95-0.125,0.95-0.10]) pylab.axes([0.15,0.35,0.95-0.15,0.95-0.35]) data_experiments = model.data.experiments #data_experiments = sorted(model.data.experiments) for independentValues in data_experiments: Xdata = model.data.X[independentValues] Ydata = model.data.Y[independentValues] Xtheory = scipy.logspace(scipy.log10(min(Xdata)),scipy.log10(max(Xdata)),num=100) pointType = model.data.pointType[independentValues] errorBar = model.data.errorBar[independentValues] mean_theory = scipy.zeros(len(Xtheory)) std_theory = scipy.zeros(len(Xtheory)) #max_theory = scipy.zeros(len(Xdata)) #min_theory = scipy.zeros(len(Xdata)) for i in range(0, num_to_count): ens_theory = model.theory.Y(Xtheory,ens[i*sampling_freq],independentValues) mean_theory += ens_theory std_theory += (ens_theory)**2 mean_theory = mean_theory/(1.0*num_to_count) std_theory = scipy.sqrt((std_theory-num_to_count*mean_theory**2)/(num_to_count-1.)) pylab.loglog(Xdata,Ydata,pointType[1]) lb = model.getLabel(model.theory.independentNames,independentValues,pow10first=True) pylab.errorbar(Xdata,Ydata, yerr=errorBar, fmt=pointType,label=lb) pylab.loglog(Xtheory,mean_theory,pointType[0]) axis_dep=model.getAxis(Xdata,Ydata) #upper_bound = mean_theory+std_theory #lower_bound = mean_theory-std_theory upper_bound = scipy.exp(scipy.log(mean_theory) + scipy.log(1.+std_theory/mean_theory)*rescale) lower_bound = scipy.exp(scipy.log(mean_theory)+scipy.log(1.-std_theory/mean_theory)*rescale) for i in range(0, len(lower_bound)): if lower_bound[i]<=0: lower_bound[i]=10.**(-16) pylab.fill_between(Xtheory,lower_bound,y2=upper_bound,color=pointType[0],alpha=0.2) #if model==m.Models.values()[1]: #print Xdata, mean_theory-std_theory, mean_theory+std_theory, lower_bound # break for i, Ax in enumerate(axis_dep): ax0[i] =i%2 and max(ax0[i],Ax) or min(ax0[i],Ax) pylab.axis(tuple(ax0)) pylab.legend(loc=(-0.15,-0.52),ncol=3) if paper_fig: pylab.xlabel(model.theory.XnameTeX) pylab.ylabel(model.theory.YnameTeX) else: pylab.xlabel(model.theory.XnameTeX) pylab.ylabel(model.theory.YnameTeX) pylab.ion() pylab.show() return Xtheory,mean_theory, std_theory
def sampling_efficiency(self): ''' Run the code for all available sampling types. Plot the results. ''' def run_estimation(n_int, sampling_type): # instantiate spirrid with samplingetization methods print 'running', sampling_type, n_int self.s.set(n_int=n_int, sampling_type=sampling_type) n_sim = self.s.sampling.n_sim exec_time = np.sum(self.s.exec_time) return self.s.mu_q_arr, exec_time, n_sim # vectorize the estimation to accept arrays run_estimation_vct = np.vectorize(run_estimation, [object, float, int]) #=========================================================================== # Generate the inspected domain of input parameters using broadcasting #=========================================================================== run_estimation_vct([5], ['PGrid']) sampling_types = self.sampling_types sampling_colors = np.array( ['grey', 'black', 'grey', 'black'], dtype=str) # 'blue', 'green', 'red', 'magenta' sampling_linestyle = np.array(['--', '--', '-', '-'], dtype=str) # run the estimation on all combinations of n_int and sampling_types mu_q, exec_time, n_sim_range = run_estimation_vct( self.n_int_range[:, None], sampling_types[None, :]) p.rcdefaults() f = p.figure(figsize=(12, 6)) f.subplots_adjust(left=0.06, right=0.94) #=========================================================================== # Plot the results #=========================================================================== p.subplot(1, 2, 1) p.title('response for %d $n_\mathrm{sim}$' % n_sim_range[-1, -1]) for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.plot(self.e_arr, mu_q[-1, i], color=color, label=sampling, linestyle=linestyle) if len(self.exact_arr) > 0: p.plot(self.e_arr, self.exact_arr, color='black', label='Exact solution') p.legend(loc=1) p.xlabel('e', fontsize=18) p.ylabel('q', fontsize=18) # @todo: get n_sim - x-axis p.subplot(1, 2, 2) for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], exec_time[:, i], color=color, label=sampling, linestyle=linestyle) p.legend(loc=2) p.xlabel('$n_\mathrm{sim}$', fontsize=18) p.ylabel('$t$ [s]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_time_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) #=========================================================================== # Evaluate the error #=========================================================================== if len(self.exact_arr) > 0: er = ErrorEval(exact_arr=self.exact_arr) def eval_error(mu_q, error_measure): return error_measure(mu_q) eval_error_vct = np.vectorize(eval_error) error_measures = np.array( [er.eval_error_max, er.eval_error_energy, er.eval_error_rms]) error_table = eval_error_vct(mu_q[:, :, None], error_measures[None, None, :]) f = p.figure(figsize=(14, 6)) f.subplots_adjust(left=0.07, right=0.97, wspace=0.26) p.subplot(1, 2, 1) p.title('max rel. lack of fit') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 0], color=color, label=sampling, linestyle=linestyle) #p.ylim( 0, 10 ) p.legend() p.xlabel('$n_\mathrm{sim}$', fontsize=18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize=18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 2], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('$n_{\mathrm{sim}}$', fontsize=18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_error_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) f = p.figure(figsize=(14, 6)) f.subplots_adjust(left=0.07, right=0.97, wspace=0.26) p.subplot(1, 2, 1) p.title('rel. max lack of fit') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 0], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('time [s]', fontsize=18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize=18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 2], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('time [s]', fontsize=18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_error_time fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) if self.show_output: p.show()
from matplotlib.colors import LinearSegmentedColormap import matplotlib.animation as manimation # from matplotlib import pyplot as plt # import cv2 from matplotlib.ticker import FormatStrFormatter from scipy.stats.stats import pearsonr from scipy.stats import linregress import re from scipy.optimize import curve_fit import sympy as sym from decimal import Decimal from matplotlib.patches import Circle import matplotlib.cm as cm from matplotlib.ticker import FormatStrFormatter from mpl_toolkits.axes_grid1.inset_locator import InsetPosition import matplotlib.pyplot as plt; plt.rcdefaults() from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import LogNorm from scipy.stats import sem, t path_out=r'D:\Github_code' def main(): test() plot_test() def test(): circle_radius=np.zeros((5,3)) circle_radius[:,0]=np.random.randint(0,5,5)
def sampling_efficiency(self): ''' Run the code for all available sampling types. Plot the results. ''' def run_estimation(n_int, sampling_type): # instantiate spirrid with samplingetization methods print 'running', sampling_type, n_int self.s.set(n_int = n_int, sampling_type = sampling_type) n_sim = self.s.sampling.n_sim exec_time = np.sum(self.s.exec_time) return self.s.mu_q_arr, exec_time, n_sim # vectorize the estimation to accept arrays run_estimation_vct = np.vectorize(run_estimation, [object, float, int]) #=========================================================================== # Generate the inspected domain of input parameters using broadcasting #=========================================================================== run_estimation_vct([5], ['PGrid']) sampling_types = self.sampling_types sampling_colors = np.array(['grey', 'black', 'grey', 'black'], dtype = str) # 'blue', 'green', 'red', 'magenta' sampling_linestyle = np.array(['--', '--', '-', '-'], dtype = str) # run the estimation on all combinations of n_int and sampling_types mu_q, exec_time, n_sim_range = run_estimation_vct(self.n_int_range[:, None], sampling_types[None, :]) p.rcdefaults() f = p.figure(figsize = (12, 6)) f.subplots_adjust(left = 0.06, right = 0.94) #=========================================================================== # Plot the results #=========================================================================== p.subplot(1, 2, 1) p.title('response for %d $n_\mathrm{sim}$' % n_sim_range[-1, -1]) for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.plot(self.e_arr, mu_q[-1, i], color = color, label = sampling, linestyle = linestyle) if len(self.exact_arr) > 0: p.plot(self.e_arr, self.exact_arr, color = 'black', label = 'Exact solution') p.legend(loc = 1) p.xlabel('e', fontsize = 18) p.ylabel('q', fontsize = 18) # @todo: get n_sim - x-axis p.subplot(1, 2, 2) for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], exec_time[:, i], color = color, label = sampling, linestyle = linestyle) p.legend(loc = 2) p.xlabel('$n_\mathrm{sim}$', fontsize = 18) p.ylabel('$t$ [s]', fontsize = 18) if self.save_output: basename = self.fname_sampling_efficiency_time_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi = self.dpi) #=========================================================================== # Evaluate the error #=========================================================================== if len(self.exact_arr) > 0: er = ErrorEval(exact_arr = self.exact_arr) def eval_error(mu_q, error_measure): return error_measure(mu_q) eval_error_vct = np.vectorize(eval_error) error_measures = np.array([er.eval_error_max, er.eval_error_energy, er.eval_error_rms ]) error_table = eval_error_vct(mu_q[:, :, None], error_measures[None, None, :]) f = p.figure(figsize = (14, 6)) f.subplots_adjust(left = 0.07, right = 0.97, wspace = 0.26) p.subplot(1, 2, 1) p.title('max rel. lack of fit') for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 0], color = color, label = sampling, linestyle = linestyle) #p.ylim( 0, 10 ) p.legend() p.xlabel('$n_\mathrm{sim}$', fontsize = 18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize = 18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 2], color = color, label = sampling, linestyle = linestyle) p.legend() p.xlabel('$n_{\mathrm{sim}}$', fontsize = 18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize = 18) if self.save_output: basename = self.fname_sampling_efficiency_error_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi = self.dpi) f = p.figure(figsize = (14, 6)) f.subplots_adjust(left = 0.07, right = 0.97, wspace = 0.26) p.subplot(1, 2, 1) p.title('rel. max lack of fit') for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 0], color = color, label = sampling, linestyle = linestyle) p.legend() p.xlabel('time [s]', fontsize = 18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize = 18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate(zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 2], color = color, label = sampling, linestyle = linestyle) p.legend() p.xlabel('time [s]', fontsize = 18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize = 18) if self.save_output: basename = self.fname_sampling_efficiency_error_time fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi = self.dpi) if self.show_output: p.show()
prob_matrix, X, Y = scipy.histogram2d(U.field('BPZ_Z_B') - 0 * scipy.ones(len(U.field('BPZ_Z_B'))), C.field('zp_best'), bins=[xbins, ybins]) prob_matrix = prob_matrix / prob_matrix.max() import pylab #X, Y = pylab.meshgrid(zs_copy,zs_copy) print prob_matrix.shape, X.shape, Y.shape import pylab pylab.rcdefaults() params = { 'backend': 'ps', 'text.usetex': True, 'ps.usedistiller': 'xpdf', 'ps.distiller.res': 6000 } pylab.rcParams.update(params) fig_size = [8, 8] params = { 'axes.labelsize': 20, 'text.fontsize': 22, 'legend.fontsize': 22, 'xtick.labelsize': 20,
def _multi_bar_plot(self, title_lst, legend_lst, time_arr, error_lst, n_sim_lst): '''Plot the results if the code efficiency. ''' p.rcdefaults() fsize = 14 fig = p.figure(figsize = (15, 3)) rc('font', size = fsize) rc('legend', fontsize = fsize - 2) legend_lst = ['weave', 'cython', 'numpy'] # times are stored in 3d array - dimensions are: n_sampling, n_lang, n_run, n_times = time_arr.shape print 'arr', time_arr.shape times_sum = np.sum(time_arr, axis = n_times) p.subplots_adjust(left = 0.1, right = 0.95, wspace = 0.1, bottom = 0.15, top = 0.8) for meth_i in range(n_sampling): ax1 = fig.add_subplot(1, n_sampling, meth_i + 1) ax1.set_xlabel('execution time [s]') ytick_pos = np.arange(n_lang) + 1 # ax1.axis([0, x_max_plt, 0, n_lang]) # todo: **2 n_vars if len(self.exact_arr) > 0: ax1.set_title('%s: $ n_\mathrm{sim} = %s, \mathrm{e}_\mathrm{rms}=%s, \mathrm{e}_\mathrm{max}=%s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]), self._formatSciNotation('%.2e' % error_lst[meth_i][0]), self._formatSciNotation('%.2e' % error_lst[meth_i][1]))) else: ax1.set_title('%s: $ n_\mathrm{sim} = %s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]))) ax1.set_yticks(ytick_pos) if meth_i == 0: ax1.set_yticklabels(legend_lst, fontsize = fsize + 2) else: ax1.set_yticklabels([]) ax1.set_xlim(0, 1.2 * np.max(times_sum[meth_i])) distance = 0.2 height = 1.0 / n_run - distance offset = height / 2.0 colors = ['w', 'w', 'w', 'r', 'y', 'b', 'g', 'm' ] hatches = [ '/', '\\', 'x', '-', '+', '|', 'o', 'O', '.', '*' ] label_lst = ['sampling', 'compilation', 'integration'] for i in range(n_run): pos = np.arange(n_lang) + 1 - offset + i * height end_bar_pos = np.zeros((n_lang,), dtype = 'd') for j in range(n_times): if i > 0: label = label_lst[j] else: label = None bar_lengths = time_arr[meth_i, :, i, j] rects = ax1.barh(pos, bar_lengths , align = 'center', height = height, left = end_bar_pos, color = colors[j], edgecolor = 'k', hatch = hatches[j], label = label) end_bar_pos += bar_lengths for k in range(n_lang): x_val = times_sum[meth_i, k, i] + 0.01 * np.max(times_sum[meth_i]) ax1.text(x_val, pos[k], '$%4.2f\,$s' % x_val, horizontalalignment = 'left', verticalalignment = 'center', color = 'black')#, weight = 'bold') if meth_i == 0: ax1.text(0.02 * np.max(times_sum[0]), pos[k], '$%i.$' % (i + 1), horizontalalignment = 'left', verticalalignment = 'center', color = 'black', bbox = dict(pad = 0., ec = "w", fc = "w")) p.legend(loc = 0)
def plot_SeveralCurvesOnOnePlot(self, selfExt, showTitle, showYLabel, showXLabel, showLegend, showGrid, showReferenceCurve, showSlopedStraightLineReferenceCurve, showHorizontalStraightLineReferenceCurve, showVerticalStraightLineReferenceCurve, colorBackground, colorPlotBorder, colorXYLabels, colorXTicks, colorYTicks, colorTitle, fontsizeTitle, fontsizeXYLabels, fontsizeXTicks, fontsizeYTicks, fontsizeLegend, valueTitle, valueLabelY, valueLabelX, valueLegendLocation, valuesLegendLabels, valueRefCurveMultiplier, valueRefCurveLabel, valueSlopedStraightLineRefCurveLabel, valueHorizontalStraightLineRefCurveLabel, valueVerticalStraightLineRefCurveLabel, valuesRefCurvePlotYList, valuesRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList, valuesSlopedStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList, valuesHorizontalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList, valuesVerticalStraightLineRefCurvePlotXList, plotStyle, plotBaseX, plotBaseY, lineWidth, markerSize ): ''' Calls pylab.plot to do the actual plotting; data is specified. These are NOT demo plots. Max number of plots: 25 + 1 reference curve Variables: self.plot_X[] (x list of length 1) self.plot_Y[] (y list of lists of variable length) Plot Options: self.plotOptions (list of third argument plot line colors, line styles, line markers) plotOptions_SubPlot (number determining rows x columns x plot_number) Labels and such from handlerPlotPreprocess: plot title: button status self.varCheckbuttonShowTitle_AllCurvesOnePlot.get() value self.varShowTitle_AllCurvesOnePlot.get() y label: button status self.varCheckbuttonShowLabelY_AllCurvesOnePlot.get() value self.varShowLabelY_AllCurvesOnePlot.get() x label: button status self.varCheckbuttonShowLabelX_AllCurvesOnePlot.get() value self.varShowLabelX_AllCurvesOnePlot.get() show grid: button status self.varCheckbuttonShowGrid_AllCurvesOnePlot.get() reference curve: button status self.varCheckbuttonShowReferenceCurve_AllCurvesOnePlot.get() scale self.comboboxShowReferenceCurveMultiplier_AllCurvesOnePlot.get() curve self.comboboxShowReferenceCurveLabeled_AllCurvesOnePlot.get() ''' if DEBUG: print('\n-- DEBUG --') print('showTitle: %s (%s)' % (showTitle, type(showTitle))) print('showYLabel: %s (%s)' % (showYLabel,type(showYLabel))) print('showXLabel: %s (%s)' % (showXLabel,type(showXLabel))) print('showLegend: %s (%s)' % (showLegend,type(showLegend))) print('showGrid: %s (%s)' % (showGrid,type(showGrid))) print('showReferenceCurve: %s (%s)' % (showReferenceCurve,type(showReferenceCurve))) print('showSlopedStraightLineReferenceCurve: %s (%s)' % ( showSlopedStraightLineReferenceCurve, type(showSlopedStraightLineReferenceCurve)) ) print('showHorizontalStraightLineReferenceCurve: %s (%s)' % ( showHorizontalStraightLineReferenceCurve, type(showHorizontalStraightLineReferenceCurve)) ) print('showVerticalStraightLineReferenceCurve: %s (%s)' % ( showVerticalStraightLineReferenceCurve, type(showVerticalStraightLineReferenceCurve)) ) print('colorBackground: %s (%s)' % (colorBackground,type(colorBackground))) print('colorXYLabels: %s (%s)' % (colorXYLabels,type(colorXYLabels))) print('colorXTicks: %s (%s)' % (colorXTicks,type(colorXTicks))) print('colorYTicks: %s (%s)' % (colorYTicks,type(colorYTicks))) print('colorTitle: %s (%s)' % (colorTitle,type(colorTitle))) print('fontsizeTitle: %s (%s)' % (fontsizeTitle,type(fontsizeTitle))) print('fontsizeXYLabels: %s (%s)' % (fontsizeXYLabels,type(fontsizeXYLabels))) print('fontsizeXTicks: %s (%s)' % (fontsizeXTicks,type(fontsizeXTicks))) print('fontsizeYTicks: %s (%s)' % (fontsizeYTicks,type(fontsizeYTicks))) print('fontsizeLegend: %s (%s)' % (fontsizeLegend,type(fontsizeLegend))) print('valueTitle: %s (%s)' % (valueTitle,type(valueTitle))) print('valueLabelY: %s (%s)' % (valueLabelY,type(valueLabelY))) print('valueLabelX: %s (%s)' % (valueLabelX,type(valueLabelX))) print('valueLegendLocation: %s (%s)' % (valueLegendLocation,type(valueLegendLocation))) print('valuesLegendLabels: %s (%s)' % (valuesLegendLabels,type(valuesLegendLabels))) print('valueRefCurveMultiplier: %s (%s)' % (valueRefCurveMultiplier,type(valueRefCurveMultiplier))) print('valueRefCurveLabel: %s (%s)' % (valueRefCurveLabel,type(valueRefCurveLabel))) print('valueSlopedStraightLineRefCurveLabel: %s (%s)' % ( valueSlopedStraightLineRefCurveLabel, type(valueSlopedStraightLineRefCurveLabel)) ) print('valueHorizontalStraightLineRefCurveLabel: %s (%s)' % ( valueHorizontalStraightLineRefCurveLabel, type(valueHorizontalStraightLineRefCurveLabel)) ) print('valueVerticalStraightLineRefCurveLabel: %s (%s)' % ( valueVerticalStraightLineRefCurveLabel, type(valueVerticalStraightLineRefCurveLabel)) ) print('valuesRefCurvePlotYList: %s (%s)' % ( valuesRefCurvePlotYList, type(valuesRefCurvePlotYList)) ) print('valuesRefCurvePlotXList: %s (%s)' % ( valuesRefCurvePlotXList, type(valuesRefCurvePlotXList)) ) print('valuesSlopedStraightLineRefCurvePlotYList: %s (%s)' % ( valuesSlopedStraightLineRefCurvePlotYList, type(valuesSlopedStraightLineRefCurvePlotYList)) ) print('valuesSlopedStraightLineRefCurvePlotXList: %s (%s)' % ( valuesSlopedStraightLineRefCurvePlotXList, type(valuesSlopedStraightLineRefCurvePlotXList)) ) print('valuesHorizontalStraightLineRefCurvePlotYList: %s (%s)' % ( valuesHorizontalStraightLineRefCurvePlotYList, type(valuesHorizontalStraightLineRefCurvePlotYList)) ) print('valuesHorizontalStraightLineRefCurvePlotXList: %s (%s)' % ( valuesHorizontalStraightLineRefCurvePlotXList, type(valuesHorizontalStraightLineRefCurvePlotXList)) ) print('valuesVerticalStraightLineRefCurvePlotYList: %s (%s)' % ( valuesVerticalStraightLineRefCurvePlotYList, type(valuesVerticalStraightLineRefCurvePlotYList)) ) print('valuesVerticalStraightLineRefCurvePlotXList: %s (%s)' % ( valuesVerticalStraightLineRefCurvePlotXList, type(valuesVerticalStraightLineRefCurvePlotXList)) ) print('plotStyle: %s (%s)' % (plotStyle,type(plotStyle))) print('plotBaseX: %s (%s)' % (plotBaseX,type(plotBaseX))) print('plotBaseY: %s (%s)' % (plotBaseY,type(plotBaseY))) print('lineWidth: %s (%s)' % (lineWidth,type(lineWidth))) print('markerSize: %s (%s)' % (markerSize,type(markerSize))) print('-- END OF DEBUG --\n') # destroy old popup # try: # self.frame_ToplevelPylabPlotMySQL.destroy() # except: # pass # determine dimension of subplot, upto 'numberCurvesMax' plots max lenYList = len(self.plot_Y) # tells how many curves, and therefore how many plots, are to be drawn # bounds check; no more than 'numberCurvesMax' plots in a 5x5 array allowed; if lenYList > numberCurvesMax: stringLenYList = ( 'Number of curves to plot is out of range:\n\n' + ' Number of curves attempted: ' + str(lenYList) + '\n' + ' Max number of curves allowed: ' + str(numberCurvesMax) + '\n\n' + 'To continue with plotting the first ' + str(numberCurvesMax) + '\n' + ' of ' + str(lenYList) + ' curves selected, click "OK".' + '\n\n' + 'To halt plotting, click "CANCEL".' + '\n' ) ans = askokcancel( 'Max number of curves exceeded', stringLenYList ) if not ans: return else: lenYList = numberCurvesMax # print figure number: if DEBUG: print( '\n------------------\n' + 'In module_PylabPlotMySQL_All\n' + ' self.numberPylabPlotFigure = %s' ) % self.numberPylabPlotFigure # reset defaults pylab.rcdefaults() # tell pylab which figue we are dealing with; otherwise, defaults to Figure 1, which conflicts with regular x-y plots pylab.figure( self.numberPylabPlotFigure, facecolor=colorPlotBorder ) # color plot border # pylab.figure().patch.set_facecolor(colorPlotBorder) # clear the figure if not self.keepPreviousPlot: pylab.clf() # set some plot params params = { 'axes.facecolor' : colorBackground, #colorChartBackground, # plot bg USE THIS! 'axes.labelsize' : int(fontsizeXYLabels), #fontsizeChartLabels, 'axes.labelcolor' : colorXYLabels, #colorChartLabels, # x-y labels 'xtick.labelsize' : int(fontsizeXTicks), #fontsizeXTickLabels, 'xtick.color' : colorXTicks, #colorXTickLabels, 'ytick.labelsize' : int(fontsizeYTicks), #fontsizeYTickLabels, 'ytick.color' : colorYTicks, #colorYTickLabels, 'legend.fontsize' : int(fontsizeLegend), # 'lines.linewidth' : lineWidth, # width of data plot lines and legend labels (0=thin, 5=thick) # 'figure.titlesize': 24, # 'figure.facecolor' : 'darkgray', # 'figure.edgecolor' : 'cyan', # 'figure.figsize' : [float(widthChartFigure), float(heightChartFigure)], # 'axes.titlesize' : 8, #fontsizeChartTitle, } # update the params pylab.rcParams.update(params) # create plots # ... only one plot; all curves on one plot subplot=111 # ... define subplot FIRST before defining other parameters self.pylabSubplot = pylab.subplot(subplot) # ... apply grid pylab.grid(showGrid) # ... x and y labels if showXLabel: pylab.xlabel(valueLabelX) if showYLabel: pylab.ylabel(valueLabelY) # ... plot title if showTitle: pylab.title( valueTitle, color=colorTitle, size=fontsizeTitle ) if DEBUG: print( '\nmodule_PylabPlotMySQL_All self.plot_X = ' ) print(self.plot_X) print( '\nmodule_PylabPlotMySQL_All self.plot_Y = ' ) print(self.plot_Y) if lenYList > numberCurvesMax: stringErrorNumberPlot = ( 'Number of curves requested for plotting is over\n' + 'the maximum:\n\n' + ' number of curves requested: %s\n' + ' number of curves allowed: %s\n\n' + 'Reduce the number of curves to be plotted and try again.' ) % ( lenYList, numberCurvesMax ) print stringErrorNumberPlot showinfo( 'Error: too many curves', stringErrorNumberPlot ) return # keep track of global values for xMin, yMin, xMax, yMax self.xMin_Global = [] self.xMax_Global = [] self.yMin_Global = [] self.yMax_Global = [] # ... plot x-y for numberPlot in range(lenYList): module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, self.plot_X[numberPlot], self.plot_Y[numberPlot], self.plotOptions[numberPlot], lineWidth, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self,self.plot_X[numberPlot], self.plot_Y[numberPlot] ) # reference plot, if desired if showReferenceCurve: stringInvalidMultiplier = ( 'Unable to plot reference curve:' + '\n' ' Invalid value for reference curve multiplier.\n' + ' Multiplier must be a string representing either\n' + ' an integer, float, or fraction (e.g., 1/5).\n' ) # change multiplier to decimal tempMult = valueRefCurveMultiplier # print 'tempMult, type = ',tempMult,type(tempMult) if tempMult == '1/10': multiplier = 1./10. elif tempMult == '1/9': multiplier = 1./9. elif tempMult == '1/8': multiplier = 1./8. elif tempMult == '1/7': multiplier = 1./7. elif tempMult == '1/6': multiplier = 1./6. elif tempMult == '1/5': multiplier = 1./5. elif tempMult == '1/4': multiplier = 1./4. elif tempMult == '1/3': multiplier = 1./3. elif tempMult == '1/2': multiplier = 1./2. elif tempMult == '2': multiplier = 2. elif tempMult == '3': multiplier = 3. elif tempMult == '4': multiplier = 4. elif tempMult == '5': multiplier = 5. elif tempMult == '6': multiplier = 6. elif tempMult == '7': multiplier = 7. elif tempMult == '8': multiplier = 8. elif tempMult == '9': multiplier = 9. elif tempMult == '10': multiplier = 10. elif tempMult.count('/') == 1: # just one division sign is present in string, so try arbitrary fraction; if fails, nothing left to try tempMult_New = tempMult.split('/') try: multiplier = float(tempMult_New[0]) / float(tempMult_New[1]) except: # form error string selfExt.MySQL_Output( 1, stringInvalidMultiplier ) showinfo( 'Error: invalid value', '\n' + stringInvalidMultiplier + '\n' ) return else: # last ditch chance to just float the string representing a number; if fails, nothing left to try try: multiplier = float(valueRefCurveMultiplier) except: selfExt.MySQL_Output( 1, stringInvalidMultiplier ) showinfo( 'Error: invalid value', '\n' + stringInvalidMultiplier + '\n' ) return # choose correct X-values for reference curve plot_X_RefCurve = valuesRefCurvePlotXList plot_Y_RefCurve = [float(y)*float(multiplier) for y in valuesRefCurvePlotYList] # ... set up plots module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, plot_X_RefCurve, plot_Y_RefCurve, 'r--d', lineWidth, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self,plot_X_RefCurve,plot_Y_RefCurve ) # sloped straight-line reference curve, if desired if showSlopedStraightLineReferenceCurve: module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesSlopedStraightLineRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList, 'r--s', lineWidth, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesSlopedStraightLineRefCurvePlotXList, valuesSlopedStraightLineRefCurvePlotYList ) # horizontal straight-line reference curve, if desired if showHorizontalStraightLineReferenceCurve: # ... no need to error check; validation done in "X-Y PLOTTING SPECS" window module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesHorizontalStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList, 'r--s', lineWidth, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesHorizontalStraightLineRefCurvePlotXList, valuesHorizontalStraightLineRefCurvePlotYList ) # vertical straight-line reference curve, if desired if showVerticalStraightLineReferenceCurve: module_PlotUtilities.plotStyleForCurve( self, pylab, plotStyle, valuesVerticalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList, 'r--s', lineWidth, markerSize, plotBaseX, plotBaseY, ) module_PlotUtilities.globalMinMaxValues( self, valuesVerticalStraightLineRefCurvePlotXList, valuesVerticalStraightLineRefCurvePlotYList ) # display legend # print '\nself.legend_buttonStatus = %s\n' % self.legend_buttonStatus if showLegend: if DEBUG: print '\n====\nvaluesLegendLabels:\n',valuesLegendLabels # set legend shadow stringLegendShadow = 'True' # legend labels stringLegendLabels = [] # lenLabels = len(self.plot_Labels) lenLabels = len(valuesLegendLabels) # for label in self.plot_Labels: for label in valuesLegendLabels: stringLegendLabels.append(label) if showReferenceCurve: # include reference curve in legend # stringLegendLabels.append(str(multiplier) + ' * ' + self.refCurveLabel) stringLegendLabels.append( str(valueRefCurveMultiplier) + ' * (' + valueRefCurveLabel + ') [ref]' ) if showSlopedStraightLineReferenceCurve: # include horizontal straight-line reference curve in legend stringLegendLabels.append( # 'straight line [ref]' valueSlopedStraightLineRefCurveLabel ) if showHorizontalStraightLineReferenceCurve: # include horizontal straight-line reference curve in legend stringLegendLabels.append( # 'straight line [ref]' valueHorizontalStraightLineRefCurveLabel ) if showVerticalStraightLineReferenceCurve: # include vertical straight-line reference curve in legend stringLegendLabels.append( # 'straight line [ref]' valueVerticalStraightLineRefCurveLabel ) # form legend pylab.legend( tuple(stringLegendLabels), loc=valueLegendLocation, shadow=stringLegendShadow ) if plotStyle == 'semilogx' or plotStyle == 'loglog': if plotBaseX == 'e': xMin_Local = min(self.xMin_Global) xMax_Local = max(self.xMax_Global) okXLabels = module_PlotUtilities.formNewXLabels( self,pylab,xMin_Local,xMax_Local,colorXTicks,fontsizeXTicks ) if not okXLabels: return if plotStyle == 'semilogy' or plotStyle == 'loglog': if plotBaseY == 'e': yMin_Local = min(self.yMin_Global) yMax_Local = max(self.yMax_Global) okYLabels = module_PlotUtilities.formNewYLabels( self,pylab,yMin_Local,yMax_Local,colorYTicks,fontsizeYTicks ) if not okYLabels: return # graph the plot pylab.show() return