示例#1
0
 def testFancyErrorPlot(self):
     ''' test a plot with error bands with separate upper and lower limits '''
     fig, ax = getFigAx(1,
                        name=sys._getframe().f_code.co_name[4:],
                        **figargs)  # use test method name as title
     assert fig.__class__.__name__ == 'MyFigure'
     assert fig.axes_class.__name__ == 'MyAxes'
     assert not isinstance(ax,
                           (list, tuple))  # should return a "naked" axes
     var1 = self.var1
     var2 = self.var2
     err1 = self.err1
     err2 = self.err2
     # create plot
     plts = ax.linePlot([var1, var2],
                        errorband=[err1, err2],
                        edgecolor=('k', 1),
                        expand_list=('edgecolor', ),
                        ylabel='Variables with Error Bands [{1:s}]',
                        llabel=True,
                        ylim=var1.limits(),
                        legend=2,
                        hline=2.,
                        vline=(2, 3))
     assert len(plts) == 2
     # add label
     ax.addLabel(label=0,
                 loc=4,
                 lstroke=False,
                 lalphabet=True,
                 size=None,
                 prop=None)
示例#2
0
  def testBasicTaylorPlot(self):
    ''' test a simple Taylor plot with two variables/timeseries and a reference '''    
    fig,ax = getFigAx(1, lTaylor=True, axes_args=dict(std=1.2, leps=True),
                       name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
    assert fig.__class__.__name__ == 'MyFigure'
    assert fig.axes_class.__name__ == 'TaylorAxes'
    assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
    var0 = self.var0; var1 = self.var1; var2 = self.var2
    # set up reference
#     print(ax.setReference(var0))
#     ax.showRefLines()
    # add some dots...
    plts, = ax.taylorPlot([var1, var2], reference=var0, rmse_lines=6)
    assert len(plts) == 2
    plts, = ax.taylorPlot([var1*1.5, var2/2., var0], reference='Reference', loverride=True)
    assert len(plts) == 2
    # add a negative correlation
    negvar1 = var1 * -1
    plts, = ax.taylorPlot(negvar1, legend=1, lprint=True, label_ext=' (neg.)')
    assert len(plts) == 1
    # add a random variable (should have no correlation
    plts, = ax.taylorPlot(self.var3, legend=1, pval=0.01, lprint=True, linsig=True)
    assert len(plts) == 1
    # add label
    ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#3
0
 def testFancyErrorPlot(self):
     """ test a plot with error bands with separate upper and lower limits """
     fig, ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs)  # use test method name as title
     assert fig.__class__.__name__ == "MyFigure"
     assert fig.axes_class.__name__ == "MyAxes"
     assert not isinstance(ax, (list, tuple))  # should return a "naked" axes
     var1 = self.var1
     var2 = self.var2
     err1 = self.err1
     err2 = self.err2
     # create plot
     plts = ax.linePlot(
         [var1, var2],
         errorband=[err1, err2],
         edgecolor=("k", 1),
         expand_list=("edgecolor",),
         ylabel="Variables with Error Bands [{UNITS:s}]",
         llabel=True,
         ylim=var1.limits(),
         legend=2,
         hline=2.0,
         vline=(2, 3),
     )
     assert len(plts) == 2
     # add label
     ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#4
0
 def testFancyBandPlot(self):
     """ test a fancy error plot with two lines and their errors in transparent bands """
     fig, ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs)  # use test method name as title
     assert fig.__class__.__name__ == "MyFigure"
     assert fig.axes_class.__name__ == "MyAxes"
     assert not isinstance(ax, (list, tuple))  # should return a "naked" axes
     var1 = self.var1
     var2 = self.var2
     lowvar1 = self.var1 - 1.0
     lowvar2 = None  # self.var2 / 2.
     upvar1 = self.var1 * 2.0
     upvar2 = self.var2  # + 1.
     # create plot
     bnds = ax.bandPlot(upper=[upvar1, upvar2], lower=[lowvar1, lowvar2], edgecolor=0.1)
     assert len(bnds) == 2
     plts = ax.linePlot(
         [var1, var2],
         ylabel="Variables with Difference Bands [{UNITS:s}]",
         llabel=True,
         ylim=var1.limits(),
         legend=2,
     )
     assert len(plts) == 2
     # add label
     ax.addLabel(label="Fancy\nError\nBands", loc=4, lstroke=False, size=None, prop=None)
示例#5
0
 def testMeanAxisPlot(self):
     """ test a simple errorbar plot with a parasitic axes showing the means """
     fig, ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs)  # use test method name as title
     assert fig.__class__.__name__ == "MyFigure"
     assert fig.axes_class.__name__ == "MyAxes"
     assert not isinstance(ax, (list, tuple))  # should return a "naked" axes
     var1 = self.var1
     var2 = self.var2
     err1 = self.err1
     err2 = self.err2
     # create plot
     plts = ax.linePlot(
         [var1, var2],
         errorbar=[err1, err2],
         lparasiteMeans=True,
         errorevery=[1, 3],
         expand_list=["errorevery"],  # expand skip interval
         ylabel="Variables with Errors [{UNITS:s}]",
         llabel=True,
         ylim=var1.limits(),
         legend=2,
         hline=2.0,
         vline=(2, 3),
     )
     assert len(plts) == 2
     # add label
     ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#6
0
 def testBootstrapCI(self):
   ''' test a line plot with confidence intervals from bootstrapping '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   # settings
   varlist = [self.var1, self.var2]
   nbins = 15
   # add regular histogram for comparison
   bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype='bar')
   # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
   assert len(ptchs) == 2
   assert len(bins) == nbins
   vmin = np.min([var.min() for var in varlist])
   vmax = np.max([var.max() for var in varlist])
   #print bins[0], vmin; print bins[-1], vmax
   assert bins[0] == vmin and bins[-1] == vmax
   # add bootstrap plot with errorbars    
   support = np.linspace(vmin, vmax, 100)
   fitvars = [var.fitDist(dist=self.dist,lflatten=True, lbootstrap=True, nbs=1000) for var in varlist] 
   ax.bootPlot(fitvars[0], support=support, errorscale=0.5, linewidth=2, lsmooth=False,
               percentiles=None, lvar=True, lvarBand=False, lmean=True, reset_color=True)
   ax.bootPlot(fitvars[1], support=support, errorscale=0.5, linewidth=2, lsmooth=False,
               percentiles=(0.25,0.75), lvar=False, lvarBand=False, lmedian=True, reset_color=False)  
   # add the actual distribution
   ax.linePlot(self.distVar, support=support, linewidth=1, marker='^')
   # add statistical info
   pstr = "p-values for '{:s}':\n".format(self.dist)
   for var in varlist:
     pstr += '   {:<9s}   {:3.2f}\n'.format(var.name, var.kstest(dist=self.dist, asVar=False))
   pstr += '   2-samples   {:3.2f}\n'.format(kstest(varlist[0], varlist[1], lflatten=True))
   ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#7
0
 def testCombinedLinePlot(self):
     ''' test a two panel line plot with combined legend '''
     fig, axes = getFigAx(4,
                          sharey=True,
                          sharex=True,
                          name=sys._getframe().f_code.co_name[4:],
                          **figargs)  # use test method name as title
     assert fig.__class__.__name__ == 'MyFigure'
     assert fig.axes_class.__name__ == 'MyAxes'
     assert isinstance(axes, np.ndarray)  # should return a list of axes
     var1 = self.var1
     var2 = self.var2
     # create plot
     for i, ax in enumerate(axes.ravel()):
         plts = ax.linePlot(
             [var1, var2],
             ylim=var1.limits(),
             legend=0,
         )
         ax.addTitle('Panel {:d}'.format(i + 1))
         assert len(plts) == 2
     # add common legend
     fig.addSharedLegend(plots=plts)
     # add labels
     fig.addLabels(labels=None,
                   loc=4,
                   lstroke=False,
                   lalphabet=True,
                   size=None,
                   prop=None)
     # add a line
     ax.addHline(3)
示例#8
0
 def testBasicHistogram(self):
   ''' a simple bar plot of two normally distributed samples '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   # settings
   varlist = [self.var1, self.var2]
   nbins = 15
   # create regular histogram
   bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype='bar')
   # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
   assert len(ptchs) == 2
   assert len(bins) == nbins
   vmin = np.min([var.min() for var in varlist])
   vmax = np.max([var.max() for var in varlist])
   #print bins[0], vmin; print bins[-1], vmax
   assert bins[0] == vmin and bins[-1] == vmax
   # add a KDE plot
   support = np.linspace(vmin, vmax, 100)
   kdevars = [var.kde(lflatten=True, lbootstrap=True, nbs=10) for var in varlist]
   # N.B.: the bootstrapping is just to test bootstrap tolerance in regular plotting methods
   ax.linePlot(kdevars, support=support, linewidth=2)
   # add label
   pval = kstest(varlist[0], varlist[1], lflatten=True) 
   pstr = 'p-value = {:3.2f}'.format(pval)
   ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#9
0
 def testBootstrapCI(self):
   ''' test a line plot with confidence intervals from bootstrapping '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   # settings
   varlist = [self.var1, self.var2]
   nbins = 15
   # add regular histogram for comparison
   bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype='bar')
   # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
   assert len(ptchs) == 2
   assert len(bins) == nbins
   vmin = np.min([var.min() for var in varlist])
   vmax = np.max([var.max() for var in varlist])
   #print bins[0], vmin; print bins[-1], vmax
   assert bins[0] == vmin and bins[-1] == vmax
   # add bootstrap plot with errorbars    
   support = np.linspace(vmin, vmax, 100)
   fitvars = [var.fitDist(dist=self.dist,lflatten=True, lbootstrap=True, nbs=1000) for var in varlist] 
   ax.bootPlot(fitvars[0], support=support, errorscale=0.5, linewidth=2, lsmooth=False,
               percentiles=None, lvar=True, lvarBand=False, lmean=True, reset_color=True)
   ax.bootPlot(fitvars[1], support=support, errorscale=0.5, linewidth=2, lsmooth=False,
               percentiles=(0.25,0.75), lvar=False, lvarBand=False, lmedian=True, reset_color=False)  
   # add the actual distribution
   ax.linePlot(self.distVar, support=support, linewidth=1, marker='^')
   # add statistical info
   pstr = "p-values for '{:s}':\n".format(self.dist)
   for var in varlist:
     pstr += '   {:<9s}   {:3.2f}\n'.format(var.name, var.kstest(dist=self.dist, asVar=False))
   pstr += '   2-samples   {:3.2f}\n'.format(kstest(varlist[0], varlist[1], lflatten=True))
   ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#10
0
 def testBasicHistogram(self):
   ''' a simple bar plot of two normally distributed samples '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   # settings
   varlist = [self.var1, self.var2]
   nbins = 15
   # create regular histogram
   bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype='bar')
   # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
   assert len(ptchs) == 2
   assert len(bins) == nbins
   vmin = np.min([var.min() for var in varlist])
   vmax = np.max([var.max() for var in varlist])
   #print bins[0], vmin; print bins[-1], vmax
   assert bins[0] == vmin and bins[-1] == vmax
   # add a KDE plot
   support = np.linspace(vmin, vmax, 100)
   kdevars = [var.kde(lflatten=True, lbootstrap=True, nbs=10) for var in varlist]
   # N.B.: the bootstrapping is just to test bootstrap tolerance in regular plotting methods
   ax.linePlot(kdevars, support=support, linewidth=2)
   # add label
   pval = kstest(varlist[0], varlist[1], lflatten=True) 
   pstr = 'p-value = {:3.2f}'.format(pval)
   ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#11
0
 def testAdvancedLinePlot(self):
     ''' test more advanced options of the line plot function '''
     var1 = self.var1
     var2 = self.var2
     varatts = dict()  # set some default values
     for var in var1, var2:
         varatts[var.name] = dict(color=var.name, marker='1', markersize=15)
     fig, ax = getFigAx(1,
                        title='Fancy Plot Styles',
                        name=sys._getframe().f_code.co_name[4:],
                        variable_plotargs=varatts,
                        **figargs)  # use test method name as title
     assert fig.__class__.__name__ == 'MyFigure'
     assert fig.axes_class.__name__ == 'MyAxes'
     assert not isinstance(
         ax, (list, tuple, np.ndarray))  # should return a "naked" axes
     assert isinstance(ax.variable_plotargs, dict)
     # define fancy attributes
     plotatts = dict()  # override some defaults
     plotatts[var1.name] = dict(color='red', marker='*', markersize=5)
     # define fancy legend
     legend = dict(loc=2,
                   labelspacing=0.125,
                   handlelength=2.5,
                   handletextpad=0.5,
                   fancybox=True)
     # create plot
     plts = ax.linePlot([var1, var2],
                        linestyles=('--', '-.'),
                        plotatts=plotatts,
                        legend=legend)
     assert len(plts) == 2
示例#12
0
 def testFancyBandPlot(self):
     ''' test a fancy error plot with two lines and their errors in transparent bands '''
     fig, ax = getFigAx(1,
                        name=sys._getframe().f_code.co_name[4:],
                        **figargs)  # use test method name as title
     assert fig.__class__.__name__ == 'MyFigure'
     assert fig.axes_class.__name__ == 'MyAxes'
     assert not isinstance(ax,
                           (list, tuple))  # should return a "naked" axes
     var1 = self.var1
     var2 = self.var2
     lowvar1 = self.var1 - 1.
     lowvar2 = None  # self.var2 / 2.
     upvar1 = self.var1 * 2.
     upvar2 = self.var2  # + 1.
     # create plot
     bnds = ax.bandPlot(upper=[upvar1, upvar2],
                        lower=[lowvar1, lowvar2],
                        edgecolor=0.1)
     assert len(bnds) == 2
     plts = ax.linePlot(
         [var1, var2],
         ylabel='Variables with Difference Bands [{1:s}]',
         llabel=True,
         ylim=var1.limits(),
         legend=2,
     )
     assert len(plts) == 2
     # add label
     ax.addLabel(label='Fancy\nError\nBands',
                 loc=4,
                 lstroke=False,
                 size=None,
                 prop=None)
示例#13
0
 def testBasicLinePlot(self):
     """ test a simple line plot with two lines """
     fig, ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs)  # use test method name as title
     assert fig.__class__.__name__ == "MyFigure"
     assert fig.axes_class.__name__ == "MyAxes"
     assert not isinstance(ax, (list, tuple))  # should return a "naked" axes
     var0 = self.var0
     var1 = self.var1
     var2 = self.var2
     # create plot
     plts = ax.linePlot(
         [var1, var2],
         ylabel="custom label [{UNITS:s}]",
         llabel=True,
         ylim=var1.limits(),
         legend=2,
         hline=2.0,
         vline=(2, 3),
     )
     assert len(plts) == 2
     # add rescaled plot
     plts = ax.linePlot(var0, lrescale=True, scalefactor=2, offset=-1, llabel=True, legend=2, linestyle=":")
     assert len(plts) == 1
     # add label
     ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#14
0
 def testSamplePlot(self):
     """ test a line and band plot showing the mean/median and given percentiles """
     fig, ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs)  # use test method name as title
     assert fig.__class__.__name__ == "MyFigure"
     assert fig.axes_class.__name__ == "MyAxes"
     assert not isinstance(ax, (list, tuple))  # should return a "naked" axes
     # settings
     varlist = [self.var1, self.var2]
     nbins = 15
     # add regular histogram for comparison
     bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype="bar")
     # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
     assert len(ptchs) == 2
     assert len(bins) == nbins
     vmin = np.min([var.min() for var in varlist])
     vmax = np.max([var.max() for var in varlist])
     # print bins[0], vmin; print bins[-1], vmax
     assert bins[0] == vmin and bins[-1] == vmax
     # add bootstrap plot with errorbars
     support = np.linspace(vmin, vmax, 100)
     fitvars = [var.fitDist(dist=self.dist, lflatten=True, lbootstrap=True, nbs=1000) for var in varlist]
     # add the actual distribution
     ax.linePlot(self.distVar, support=support, linewidth=1, marker="^")
     # add simple sample (using bootstrap axis as sample
     ax.samplePlot(
         fitvars[0],
         support=support,
         linewidth=2,
         lsmooth=False,
         sample_axis="bootstrap",
         percentiles=(0.05, 0.95),
         lmedian=True,
         reset_color=True,
     )
     # replicate axis and add random noise to mean
     rndfit = fitvars[1].insertAxis(axis="sample", iaxis=0, length=100)
     rndfit.data_array += np.random.randn(*rndfit.shape) / 100.0
     ax.samplePlot(
         rndfit,
         support=support,
         linewidth=2,
         lsmooth=False,
         bootstrap_axis="bootstrap",
         sample_axis=("no_axis", "sample"),
         percentiles=(0.25, 0.75),
         lmean=True,
         reset_color=False,
     )
     # add statistical info
     pstr = "p-values for '{:s}':\n".format(self.dist)
     for var in varlist:
         pstr += "   {:<9s}   {:3.2f}\n".format(var.name, var.kstest(dist=self.dist, asVar=False))
     pstr += "   2-samples   {:3.2f}\n".format(kstest(varlist[0], varlist[1], lflatten=True))
     ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#15
0
 def testAxesGridLinePlot(self):
   ''' test a two panel line plot with combined legend '''        
   fig,axes = getFigAx(4, AxesGrid=True, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   #assert grid.__class__.__name__ == 'ImageGrid'
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyLocatableAxes'
   assert isinstance(axes,np.ndarray) # should return a list of axes
   var1 = self.var1; var2 = self.var2
   # create plot
   for ax in axes.ravel():
       plts = ax.linePlot([var1, var2], ylim=var1.limits(), legend=0)
       assert len(plts) == 2   
示例#16
0
 def testAxesGridLinePlot(self):
   ''' test a two panel line plot with combined legend '''        
   fig,axes = getFigAx(4, lAxesGrid=True, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   #assert grid.__class__.__name__ == 'ImageGrid'
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyLocatableAxes'
   assert isinstance(axes,np.ndarray) # should return a list of axes
   var1 = self.var1; var2 = self.var2
   # create plot
   for ax in axes.ravel():
       plts = ax.linePlot([var1, var2], ylim=var1.limits(), legend=0)
       assert len(plts) == 2   
示例#17
0
  def testBasicScatterPlot(self):
    ''' test a simple scatter plot with two variables '''    
    fig,ax = getFigAx(1, lTaylor=True, axes_args=dict(std=1.5),
                      name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
    assert fig.__class__.__name__ == 'MyFigure'
#     assert fig.axes_class.__name__ == 'TaylorAxes' # in this case, just regular rectilinear axes
    assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
    var0 = self.var0; var1 = self.var1; # var2 = self.var2
    # create plot
    plts = ax.scatterPlot(xvars=var0, yvars=var1, llabel=True, legend=0, lprint=True)
    assert len(plts) == 1
    # add label
    ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#18
0
def evaFigAx(subplot,
             dataset_plotargs=None,
             variable_plotargs=None,
             plot_labels=None,
             **kwargs):
    if dataset_plotargs is None: dataset_plotargs = evads_plotargs_rc
    if variable_plotargs is None: variable_plotargs = None
    if plot_labels is None: plot_labels = plot_labels_rc
    return figure.getFigAx(subplot,
                           dataset_plotargs=dataset_plotargs,
                           variable_plotargs=variable_plotargs,
                           plot_labels=plot_labels,
                           **kwargs)
示例#19
0
def evaFigAx(subplot, dataset_plotargs=None, variable_plotargs=None, plot_labels=None, **kwargs):
    if dataset_plotargs is None:
        dataset_plotargs = evads_plotargs_rc
    if variable_plotargs is None:
        variable_plotargs = None
    if plot_labels is None:
        plot_labels = plot_labels_rc
    return figure.getFigAx(
        subplot,
        dataset_plotargs=dataset_plotargs,
        variable_plotargs=variable_plotargs,
        plot_labels=plot_labels,
        **kwargs
    )
示例#20
0
 def testBasicSurfacePlot(self):
   ''' test a simple color/surface plot '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var0 = self.var0
   # create plot
   vline = (2,3)
   plt = ax.surfacePlot(var0, ylabel='custom label [{UNITS:s}]', llabel=True, lprint=True,
                        ylim=self.yax.limits(), clim=var0.limits(), hline=2., vline=vline)
   assert plt
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#21
0
 def testBasicLinePlot(self):
   ''' test a simple line plot with two lines '''    
   fig,ax = getFigAx(1, lPolarAxes=True, 
                     name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyPolarAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var0 = self.var0; var1 = self.var1
   # create plot
   plts = ax.linePlot([var0, var1], ylabel='custom label [{UNITS:s}]', llabel=True,
                      ylim=(self.Rmin,self.Rmax), legend=2, hline=1., vline=(np.pi/4.,np.pi/2.,np.pi))
   assert len(plts) == 2
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#22
0
 def testSharedColorbar(self):
   ''' test a simple shared colorbar between to surface plots '''
   name = sys._getframe().f_code.co_name[4:]    
   fig,axes = getFigAx(2, name=name, title=name, **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert isinstance(axes,(np.ndarray,list,tuple)) # should return a "naked" axes
   # create plot
   for ax,var in zip(axes,self.vars):
       ax.surfacePlot(var, lprint=True, clim=var.limits(), centroids=dict(color='black'))        
   # add labels
   fig.addLabels(loc=4, lstroke=False, lalphabet=True,)
   fig.updateSubplots(left=0.02, bottom=0.03)
   # add shared colorbar
   cbar = fig.addSharedColorbar(ax=axes[1], location='bottom', clevs=3, lunits=True, length=0.8)
   assert cbar
示例#23
0
 def testBasicErrorPlot(self):
   ''' test a simple errorbar plot with two lines and their standard deviations '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var1 = self.var1; var2 = self.var2
   err1 = self.err1; err2 = self.err2
   # create plot
   plts = ax.linePlot([var1, var2], errorbar=[err1, err2], 
                      errorevery=[1, 3,], expand_list=['errorevery'], # expand skip interval
                      ylabel='Variables with Errors [{1:s}]', llabel=True, 
                      ylim=var1.limits(), legend=2, hline=2., vline=(2,3))
   assert len(plts) == 2
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#24
0
 def testMeanAxisPlot(self):
   ''' test a simple errorbar plot with a parasitic axes showing the means '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var1 = self.var1; var2 = self.var2
   err1 = self.err1; err2 = self.err2
   # create plot
   plts = ax.linePlot([var1, var2], errorbar=[err1, err2], lparasiteMeans=True,
                      errorevery=[1, 3,], expand_list=['errorevery'], # expand skip interval
                      ylabel='Variables with Errors [{UNITS:s}]', llabel=True, 
                      ylim=var1.limits(), legend=2, hline=2., vline=(2,3))
   assert len(plts) == 2
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#25
0
 def testLogSurfacePlot(self):
   ''' test a surface plot with one logarithmic and one linear panel and a shared colorbar '''
   name = sys._getframe().f_code.co_name[4:]    
   fig,axes = getFigAx(2, name=name, title=name, **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert isinstance(axes,(np.ndarray,list,tuple)) # should return a "naked" axes
   # create plot
   expvar = ( self.var0 * 10 ).exp() # large exponents for large effects
   axes[0].surfacePlot(expvar, lprint=True, clog=False, )        
   axes[1].surfacePlot(expvar, lprint=True, clog=True, )        
   # add labels
   fig.addLabels(loc=4, lstroke=False, lalphabet=True,)
   fig.updateSubplots(left=0.02, bottom=0.03)
   # add shared colorbar
   cbar = fig.addSharedColorbar(ax=axes[0], location='bottom', clevs=3, lunits=True, length=0.8)
   assert cbar
示例#26
0
 def testBasicLinePlot(self):
   ''' test a simple line plot with two lines '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var0 = self.var0; var1 = self.var1; var2 = self.var2
   # create plot
   vline = np.datetime64('1981-05-16') if self.ldatetime else (2,3)
   plts = ax.linePlot([var1, var2], ylabel='custom label [{UNITS:s}]', llabel=True, lprint=True,
                      ylim=var1.limits(), legend=2, hline=2., vline=vline)
   assert len(plts) == 2
   # add rescaled plot
   plts = ax.linePlot(var0, lrescale=True, scalefactor=2, offset=-1, llabel=True, legend=2, linestyle=':')
   assert len(plts) == 1    
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#27
0
def climFigAx(subplot,
              dataset_plotargs=None,
              variable_plotargs=None,
              plot_labels=None,
              xtop=None,
              yright=None,
              **kwargs):
    if dataset_plotargs is None: dataset_plotargs = climds_plotargs_rc
    if variable_plotargs is None: variable_plotargs = variable_plotargs_rc
    if plot_labels is None: plot_labels = plot_labels_rc
    return figure.getFigAx(subplot,
                           dataset_plotargs=dataset_plotargs,
                           variable_plotargs=variable_plotargs,
                           plot_labels=plot_labels,
                           xtop=xtop,
                           yright=yright,
                           **kwargs)
示例#28
0
 def testCombinedLinePlot(self):
   ''' test a two panel line plot with combined legend '''    
   fig,axes = getFigAx(4, sharey=True, sharex=True, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert isinstance(axes,np.ndarray) # should return a list of axes
   var1 = self.var1; var2 = self.var2
   # create plot
   for i,ax in enumerate(axes.ravel()):
     plts = ax.linePlot([var1, var2], ylim=var1.limits(), legend=0,)
     ax.addTitle('Panel {:d}'.format(i+1))
     assert len(plts) == 2
   # add common legend
   fig.addSharedLegend(plots=plts)
   # add labels
   fig.addLabels(labels=None, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
   # add a line
   ax.addHline(3)
示例#29
0
def climFigAx(
    subplot, dataset_plotargs=None, variable_plotargs=None, plot_labels=None, xtop=None, yright=None, **kwargs
):
    if dataset_plotargs is None:
        dataset_plotargs = climds_plotargs_rc
    if variable_plotargs is None:
        variable_plotargs = variable_plotargs_rc
    if plot_labels is None:
        plot_labels = plot_labels_rc
    return figure.getFigAx(
        subplot,
        dataset_plotargs=dataset_plotargs,
        variable_plotargs=variable_plotargs,
        plot_labels=plot_labels,
        xtop=xtop,
        yright=yright,
        **kwargs
    )
示例#30
0
 def testIrregularSurfacePlot(self):
   ''' test a color/surface plot with irregular coordiante variables '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   var0 = self.var0
   # create coordiante variables
   xax,yax = var0.axes
   xx,yy = np.meshgrid(xax[:],yax[:], indexing='ij')
   xax = Variable(name='X Coordinate', units='X Units', data=xx, axes=var0.axes)
   yax = Variable(name='Y Coordinate', units='Y Units', data=yy, axes=var0.axes)
   # create plot
   plt = ax.surfacePlot(var0, flipxy=False, clog=False, xax=xax, yax=yax,
                        llabel=True, lprint=True, clim=var0.limits(),)
   assert plt
   # add label
   ax.addLabel(label=0, loc=4, lstroke=False, lalphabet=True, size=None, prop=None)
示例#31
0
 def testAdvancedLinePlot(self):
   ''' test more advanced options of the line plot function '''    
   var1 = self.var1; var2 = self.var2
   varatts = dict() # set some default values
   for var in var1,var2: varatts[var.name] = dict(color=var.name, marker='1', markersize=15)    
   fig,ax = getFigAx(1, title='Fancy Plot Styles', name=sys._getframe().f_code.co_name[4:], 
                     variable_plotargs=varatts, **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple,np.ndarray)) # should return a "naked" axes
   assert isinstance(ax.variable_plotargs, dict)
   # define fancy attributes
   plotatts = dict() # override some defaults
   plotatts[var1.name] = dict(color='red', marker='*', markersize=5)        
   # define fancy legend
   legend = dict(loc=2, labelspacing=0.125, handlelength=2.5, handletextpad=0.5, fancybox=True)
   # create plot
   plts = ax.linePlot([var1, var2], linestyles=('--','-.'), plotatts=plotatts, legend=legend)
   assert len(plts) == 2
示例#32
0
 def testSamplePlot(self):
   ''' test a line and band plot showing the mean/median and given percentiles '''    
   fig,ax = getFigAx(1, name=sys._getframe().f_code.co_name[4:], **figargs) # use test method name as title
   assert fig.__class__.__name__ == 'MyFigure'
   assert fig.axes_class.__name__ == 'MyAxes'
   assert not isinstance(ax,(list,tuple)) # should return a "naked" axes
   # settings
   varlist = [self.var1, self.var2]
   nbins = 15
   # add regular histogram for comparison
   bins, ptchs = ax.histogram(varlist, bins=nbins, legend=2, alpha=0.5, rwidth=0.8, histtype='bar')
   # histtype = 'bar' | 'barstacked' | 'step' | 'stepfilled'
   assert len(ptchs) == 2
   assert len(bins) == nbins
   vmin = np.min([var.min() for var in varlist])
   vmax = np.max([var.max() for var in varlist])
   #print bins[0], vmin; print bins[-1], vmax
   assert bins[0] == vmin and bins[-1] == vmax
   # add bootstrap plot with errorbars    
   support = np.linspace(vmin, vmax, 100)
   fitvars = [var.fitDist(dist=self.dist,lflatten=True, lbootstrap=True, nbs=1000) for var in varlist]
   # add the actual distribution
   ax.linePlot(self.distVar, support=support, linewidth=1, marker='^')
   # add simple sample (using bootstrap axis as sample 
   ax.samplePlot(fitvars[0], support=support, linewidth=2, lsmooth=False, 
                 sample_axis='bootstrap', percentiles=(0.05,0.95), lmedian=True, reset_color=True)
   # replicate axis and add random noise to mean
   rndfit = fitvars[1].insertAxis(axis='sample',iaxis=0,length=100)
   rndfit.data_array += np.random.randn(*rndfit.shape)/100. 
   ax.samplePlot(rndfit, support=support, linewidth=2, lsmooth=False, 
                 bootstrap_axis='bootstrap', sample_axis=('no_axis','sample'),
                 percentiles=(0.25,0.75), lmean=True, reset_color=False)  
   # add statistical info
   pstr = "p-values for '{:s}':\n".format(self.dist)
   for var in varlist:
     pstr += '   {:<9s}   {:3.2f}\n'.format(var.name, var.kstest(dist=self.dist, asVar=False))
   pstr += '   2-samples   {:3.2f}\n'.format(kstest(varlist[0], varlist[1], lflatten=True))
   ax.addLabel(label=pstr, loc=1, lstroke=False, lalphabet=True, size=None, prop=None)
示例#33
0
evads_plotargs_rc['MEns']            = AttrDict(color='royalblue',)    
示例#34
0
evads_plotargs_rc['EC (1940)']       = AttrDict(color='blue')
示例#35
0
  lgage = True 
  ldisc = False # scale sfroff to discharge
  lprecip = True # scale sfroff by precip bias
  # figure parameters for saving
#   sf, figformat, margins, subplot, figsize = getFigureSettings(2, cbar=False, sameSize=False)
  # make figure and axes
#   fig, axes = pyl.subplots(*subplot, sharex=True, sharey=False, facecolor='white', figsize=figsize)
#   margins = dict(bottom=0.11, left=0.11, right=.975, top=.95, hspace=0.05, wspace=0.05)
#   fig.subplots_adjust(**margins) # hspace, wspace
  nax = len(basins)
  paper_folder = '/home/data/Figures/Basins/'
#   fig = pyl.figure(1, figsize=(6.25,3.75))
#   axes = ImageGrid(fig, (0.07,0.11,0.91,0.82), nrows_ncols = (1, nax), axes_pad = 0.2, aspect=False, label_mode = "L")
  fig, axes = getFigAx((1,2), name=None, title='IC Ensemble Average (Hist., Mid-, End-Century)', 
                       title_font='x-large', figsize=(6.25,3.75),  
                       stylesheet='myggplot', lpublication=True, yright=False, xtop=False,
                       variable_plotargs=None, dataset_plotargs=None, plot_labels=None, 
                       sharex=True, AxesGrid=False, direction='row',
                       axes_pad = 0., aspect=False, margins=(0.075,0.11,0.95,0.81),)
  # loop over panels/basins
  for n,ax,basin in zip(xrange(nax),axes,basins):
#   for basin in basins:
        
    # load meteo data
    if lfield: 
      print ' - loading Data'
      unity = loadUnity_ShpTS(varlist=['precip'], shape='shpavg')
      unity = unity(shape_name=basin).load().climMean()
#       unity['precip'][:] *= 86400. # scale with basin area
      wrf = loadWRF_ShpEns(name=exp, domains=2, shape='shpavg', filetypes=['srfc','lsm'],
                           varlist=variables[:]) # WRF
      wrf = wrf(shape_name=basin).load().climMean()