예제 #1
0
파일: areastats.py 프로젝트: zhenkunl/GeoPy
            titles.append(title)
    # return dataset names
    return explist, titles, linestyles


## start computation
if __name__ == '__main__':

    ## settings
    # settings
    lprint = False
    lpublication = False
    lpresentation = True
    paper_folder = '/home/me/Research/Extreme Value Analysis/Report/Brewer-Wilson Talk 2015/figures/'
    loadStyleSheet('default',
                   lpresentation=lpresentation,
                   lpublication=lpublication)
    # experiments
    #   expset = 'max-ens-2050'
    #   expset = 'max-ens-2100'
    #   expset = 'max-mid-diff'
    #   expset = 'max-end-diff'
    expset = 'max-ens'
    #   expset = 'erai-max-ens'
    #   expset = '3km'
    plottypes = []
    plottypes += ['temp']  #
    #   plottypes += ['precip'] #
    #   plottypes += ['sfflx']
    #   plottypes += ['flux'] #
    #   plottypes += ['precip_types'] #
예제 #2
0
def getFigAx(subplot,
             name=None,
             title=None,
             title_font='x-large',
             title_height=None,
             figsize=None,
             variable_plotargs=None,
             dataset_plotargs=None,
             plot_labels=None,
             yright=False,
             xtop=False,
             sharex=None,
             sharey=None,
             lAxesGrid=False,
             ngrids=None,
             direction='row',
             lPolarAxes=False,
             lTaylor=False,
             axes_pad=None,
             add_all=True,
             share_all=None,
             aspect=False,
             margins=None,
             label_mode='L',
             cbar_mode=None,
             cbar_location='right',
             lreduce=True,
             cbar_pad=None,
             cbar_size='5%',
             axes_class=None,
             axes_args=None,
             stylesheet=None,
             lpresentation=False,
             lpublication=False,
             figure_class=None,
             **figure_args):
    # load stylesheet
    if stylesheet is not None:
        loadStyleSheet(stylesheet,
                       lpresentation=lpresentation,
                       lpublication=lpublication)
        if stylesheet in ('myggplot', 'ggplot'):
            warn("Rewriting built-in color definitions to GG-plot defaults.")
            if dataset_plotargs is not None:
                dataset_plotargs = toGGcolors(
                    dataset_plotargs)  # modifies in-place!
    # default figure class
    if figure_class is None: figure_class = MyFigure
    elif not issubclass(figure_class, Figure): raise TypeError
    # figure out subplots
    if isinstance(subplot, (np.integer, int)):
        if subplot == 1: subplot = (1, 1)
        elif subplot == 2: subplot = (1, 2)
        elif subplot == 3: subplot = (1, 3)
        elif subplot == 4: subplot = (2, 2)
        elif subplot == 6: subplot = (2, 3)
        elif subplot == 9: subplot = (3, 3)
        else: raise NotImplementedError
    elif not (isinstance(subplot,
                         (tuple, list)) and len(subplot) == 2) and all(
                             isInt(subplot)):
        raise TypeError
    # create figure
    if figsize is None:
        if lpublication:
            if subplot == (1, 1): figsize = (3.75, 3.75)
            elif subplot == (1, 2) or subplot == (1, 3): figsize = (6.25, 3.75)
            elif subplot == (2, 1) or subplot == (3, 1): figsize = (3.75, 7)
            else: figsize = (6.25, 6.25)
        elif lpresentation:
            if subplot == (1, 2) or subplot == (1, 3): figsize = (5, 3)
            elif subplot == (2, 1) or subplot == (3, 1): figsize = (3, 5)
            else: figsize = (5, 5)
        else:
            if subplot == (1, 1): figsize = (5, 5)
            elif subplot == (1, 2) or subplot == (1, 3): figsize = (9, 5)
            elif subplot == (2, 1) or subplot == (3, 1): figsize = (5, 9)
            else: figsize = (9, 9)
    # figure out margins
    if margins is None:
        # N.B.: the rectangle definition is presumably left, bottom, width, height
        if subplot == (1, 1): margins = (0.1, 0.1, 0.85, 0.85)
        elif subplot == (1, 2) or subplot == (1, 3):
            margins = (0.06, 0.1, 0.92, 0.87)
        elif subplot == (2, 1) or subplot == (3, 1):
            margins = (0.09, 0.11, 0.88, 0.82)
        elif subplot == (2, 2) or subplot == (3, 3):
            margins = (0.06, 0.08, 0.92, 0.92)
        else:
            margins = (0.09, 0.11, 0.88, 0.82)
        if title_height is None:
            title_height = getattr(figure_class, 'title_height',
                                   0.05)  # use default from figure
        if title is not None:
            margins = margins[:3] + (margins[3] - title_height,
                                     )  # make room for title


#   # some style sheets have different label sizes
#   if stylesheet.lower() in ('myggplot','ggplot'):
#     margins = list(margins)
#     margins[0] += 0.015; margins[1] -= 0.01 # left, bottom
#     margins[2] += 0.02; margins[3] += 0.02 # width, height
# handle special TaylorPlot axes
    if lTaylor:
        if not lPolarAxes: lPolarAxes = True
        if not axes_class: axes_class = TaylorAxes
    # handle mixed Polar/Axes
    if isinstance(axes_class, (list, tuple, np.ndarray)):
        for i, axcls in enumerate(axes_class):
            if axcls is None:
                if lTaylor: axes_class[i] = TaylorAxes
                elif lPolarAxes: axes_class[i] = MyPolarAxes
                else: axes_class[i] = MyAxes
            elif axcls.lower() == 'taylor': axes_class[i] = TaylorAxes
            elif axcls.lower() == 'polar': axes_class[i] = MyPolarAxes
            elif axcls.lower() in ('regular', 'default'):
                axes_class[i] = MyAxes
            if not issubclass(axcls, Axes): raise TypeError(axcls)
    # create axes
    if lAxesGrid:
        if share_all is None: share_all = True
        if axes_pad is None: axes_pad = 0.05
        # adjust margins for ignored label pads
        margins = list(margins)
        margins[0] += 0.005
        margins[1] -= 0.02  # left, bottom
        margins[2] -= 0.005
        margins[3] -= 0.00  # width, height
        # create axes using the Axes Grid package
        if axes_class is None: axes_class = MyLocatableAxes
        fig = mpl.pylab.figure(facecolor='white',
                               figsize=figsize,
                               axes_class=axes_class,
                               FigureClass=figure_class,
                               **figure_args)
        if axes_args is None: axes_class = (axes_class, {})
        elif isinstance(axes_args, dict): axes_class = (axes_class, axes_args)
        else: raise TypeError
        from mpl_toolkits.axes_grid1 import ImageGrid
        # AxesGrid: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
        grid = ImageGrid(fig,
                         margins,
                         nrows_ncols=subplot,
                         ngrids=ngrids,
                         direction=direction,
                         axes_pad=axes_pad,
                         add_all=add_all,
                         share_all=share_all,
                         aspect=aspect,
                         label_mode=label_mode,
                         cbar_mode=cbar_mode,
                         cbar_location=cbar_location,
                         cbar_pad=cbar_pad,
                         cbar_size=cbar_size,
                         axes_class=axes_class)
        # return figure and axes
        axes = np.asarray(grid).reshape(subplot)  # don't want flattened array
        #axes = tuple([ax for ax in grid]) # this is already flattened
    elif isinstance(axes_class, (list, tuple, np.ndarray)):
        # PolarAxes can't share axes and by default don't have labels
        if figure_args is None: figure_args = dict()
        fig = figure(facecolor='white',
                     figsize=figsize,
                     FigureClass=figure_class,
                     **figure_args)
        # now create list of axes
        if axes_args is None: axes_args = dict()
        axes = np.empty(subplot, dtype=object)
        n = 0
        for i in range(subplot[0]):
            for j in range(subplot[1]):
                n += 1
                axes[i, j] = fig.add_subplot(subplot[0],
                                             subplot[1],
                                             n,
                                             axes_class=axes_class[n - 1],
                                             aspect=aspect,
                                             **axes_args)
        # just adjust margins
        if axes_pad is None: axes_pad = 0.03
        wspace = hspace = 0.1
        margin_dict = dict(left=margins[0],
                           bottom=margins[1],
                           right=margins[0] + margins[2],
                           top=margins[1] + margins[3],
                           wspace=wspace,
                           hspace=hspace)
        fig.subplots_adjust(**margin_dict)
    else:
        # select default axes based on other arguments
        if axes_class is None:
            if lPolarAxes:
                axes_class = MyPolarAxes
                share_all = sharex = sharey = False
                # N.B.: PolarAxes does not support sharing of axes, and
                #       default behavior is to hide labels
            else:
                axes_class = MyAxes
        # create axes using normal subplot routine
        if axes_pad is None: axes_pad = 0.03
        wspace = hspace = axes_pad
        if share_all:
            sharex = 'all'
            sharey = 'all'
        if sharex is True or sharex is None: sharex = 'col'  # default
        if sharey is True or sharey is None: sharey = 'row'
        if sharex: hspace -= 0.015
        if sharey: wspace -= 0.015
        # other axes arguments
        if axes_args is not None and not isinstance(axes_args, dict):
            raise TypeError
        # create figure
        from matplotlib.pyplot import subplots
        # GridSpec: http://matplotlib.org/users/gridspec.html
        fig, axes = subplots(subplot[0],
                             subplot[1],
                             sharex=sharex,
                             sharey=sharey,
                             squeeze=lreduce,
                             facecolor='white',
                             figsize=figsize,
                             FigureClass=figure_class,
                             subplot_kw=axes_args,
                             axes_class=axes_class,
                             **figure_args)
        # there is also a subplot_kw=dict() and fig_kw=dict()
        # just adjust margins
        margin_dict = dict(left=margins[0],
                           bottom=margins[1],
                           right=margins[0] + margins[2],
                           top=margins[1] + margins[3],
                           wspace=wspace,
                           hspace=hspace)
        fig.subplots_adjust(**margin_dict)
    # apply reduction
    if lreduce:
        if isinstance(axes, np.ndarray):
            axes = axes.squeeze()  # remove singleton dimensions
            if axes.ndim == 0: axes = axes.item()
        if isinstance(axes, (list, tuple)) and len(axes) == 1:
            axes = axes[
                0]  # return a bare axes instance, if there is only one axes
    ## set label positions
    if not lPolarAxes:
        # X-/Y-labels and -ticks
        yright = not sharey and subplot[0] == 2 if yright is None else yright
        xtop = not sharex and subplot[1] == 2 if xtop is None else xtop
        if isinstance(axes, Axes):
            axes.yright = yright
            axes.xtop = xtop
        else:
            if axes.ndim == 1:
                if subplot[0] == 2: axes[-1].yright = yright  # right panel
                if subplot[1] == 2: axes[0].xtop = xtop  # top panel
            elif axes.ndim == 2:
                for ax in axes[:, -1]:
                    ax.yright = yright  # right column
                for ax in axes[0, :]:
                    ax.xtop = xtop  # top row
            else:
                raise ValueError
    # add figure title
    if name is None: name = title
    if name is not None: fig.canvas.set_window_title(name)  # window title
    if title is not None:
        y = 1. - (title_height / (5. if 'x' in title_font else 8.)
                  )  # smaller title closer to the top
        if isinstance(title_font, basestring):
            title_font = dict(fontsize=title_font, y=y)
        fig.suptitle(title, **title_font)  # title on figure (printable)
    fig.title_height = title_height  # save value
    # add default line styles for variables and datasets to axes (figure doesn't need to know)
    if isinstance(axes, np.ndarray):
        for ax in axes.ravel():
            ax.variable_plotargs = variable_plotargs
            ax.dataset_plotargs = dataset_plotargs
            ax.plot_labels = plot_labels
    else:
        axes.variable_plotargs = variable_plotargs
        axes.dataset_plotargs = dataset_plotargs
        axes.plot_labels = plot_labels
    # return Figure/ImageGrid and tuple of axes
    #if AxesGrid: fig = grid # return ImageGrid instead of figure
    return fig, axes