Changeset 3324


Ignore:
Timestamp:
Mar 28, 2018 11:49:47 PM (4 years ago)
Author:
toby
Message:

fix plot 'w' option for mpl >=1.1 & restore axis save

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIplot.py

    r3323 r3324  
    247247plotOpt['fmtChoices']  = {}
    248248
     249def MPLsubplots(figure, nrows=1, ncols=1, sharex=False, sharey=False,
     250                 squeeze=True, subplot_kw=None, gridspec_kw=None):
     251        """
     252        Copy of Figure.figure.subplots from matplotlib.figure.py
     253        Included here because this appears only in later versions of
     254        matplotlib. When v2.2 is standard, this can be removed from GSAS-II
     255       
     256        Add a set of subplots to this figure.
     257       
     258        Parameters
     259        ----------
     260        nrows, ncols : int, default: 1
     261            Number of rows/cols of the subplot grid.
     262        sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
     263            Controls sharing of properties among x (`sharex`) or y (`sharey`)
     264            axes:
     265                - True or 'all': x- or y-axis will be shared among all
     266                  subplots.
     267                - False or 'none': each subplot x- or y-axis will be
     268                  independent.
     269                - 'row': each subplot row will share an x- or y-axis.
     270                - 'col': each subplot column will share an x- or y-axis.
     271            When subplots have a shared x-axis along a column, only the x tick
     272            labels of the bottom subplot are visible.  Similarly, when
     273            subplots have a shared y-axis along a row, only the y tick labels
     274            of the first column subplot are visible.
     275        squeeze : bool, default: True
     276            - If True, extra dimensions are squeezed out from the returned
     277              axis object:
     278                - if only one subplot is constructed (nrows=ncols=1), the
     279                  resulting single Axes object is returned as a scalar.
     280                - for Nx1 or 1xN subplots, the returned object is a 1D numpy
     281                  object array of Axes objects are returned as numpy 1D
     282                  arrays.
     283                - for NxM, subplots with N>1 and M>1 are returned as a 2D
     284                  arrays.
     285            - If False, no squeezing at all is done: the returned Axes object
     286              is always a 2D array containing Axes instances, even if it ends
     287              up being 1x1.
     288        subplot_kw : dict, default: {}
     289            Dict with keywords passed to the
     290            :meth:`~matplotlib.figure.Figure.add_subplot` call used to create
     291            each subplots.
     292        gridspec_kw : dict, default: {}
     293            Dict with keywords passed to the
     294            :class:`~matplotlib.gridspec.GridSpec` constructor used to create
     295            the grid the subplots are placed on.
     296        Returns
     297        -------
     298        ax : single Axes object or array of Axes objects
     299            The added axes.  The dimensions of the resulting array can be
     300            controlled with the squeeze keyword, see above.
     301        See Also
     302        --------
     303        pyplot.subplots : pyplot API; docstring includes examples.
     304        """
     305
     306        # for backwards compatibility
     307        if isinstance(sharex, bool):
     308            sharex = "all" if sharex else "none"
     309        if isinstance(sharey, bool):
     310            sharey = "all" if sharey else "none"
     311        share_values = ["all", "row", "col", "none"]
     312        if sharex not in share_values:
     313            # This check was added because it is very easy to type
     314            # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.
     315            # In most cases, no error will ever occur, but mysterious behavior
     316            # will result because what was intended to be the subplot index is
     317            # instead treated as a bool for sharex.
     318            if isinstance(sharex, int):
     319                warnings.warn(
     320                    "sharex argument to subplots() was an integer. "
     321                    "Did you intend to use subplot() (without 's')?")
     322
     323            raise ValueError("sharex [%s] must be one of %s" %
     324                             (sharex, share_values))
     325        if sharey not in share_values:
     326            raise ValueError("sharey [%s] must be one of %s" %
     327                             (sharey, share_values))
     328        if subplot_kw is None:
     329            subplot_kw = {}
     330        if gridspec_kw is None:
     331            gridspec_kw = {}
     332
     333        # if figure.get_constrained_layout():
     334        #     gs = GridSpec(nrows, ncols, figure=figure, **gridspec_kw)
     335        # else:
     336        #     # this should turn constrained_layout off if we don't want it
     337        #     gs = GridSpec(nrows, ncols, figure=None, **gridspec_kw)
     338        gs = mpl.gridspec.GridSpec(nrows, ncols, **gridspec_kw)
     339
     340        # Create array to hold all axes.
     341        axarr = np.empty((nrows, ncols), dtype=object)
     342        for row in range(nrows):
     343            for col in range(ncols):
     344                shared_with = {"none": None, "all": axarr[0, 0],
     345                               "row": axarr[row, 0], "col": axarr[0, col]}
     346                subplot_kw["sharex"] = shared_with[sharex]
     347                subplot_kw["sharey"] = shared_with[sharey]
     348                axarr[row, col] = figure.add_subplot(gs[row, col], **subplot_kw)
     349
     350        # turn off redundant tick labeling
     351        if sharex in ["col", "all"]:
     352            # turn off all but the bottom row
     353            for ax in axarr[:-1, :].flat:
     354                ax.xaxis.set_tick_params(which='both',
     355                                         labelbottom=False, labeltop=False)
     356                ax.xaxis.offsetText.set_visible(False)
     357        if sharey in ["row", "all"]:
     358            # turn off all but the first column
     359            for ax in axarr[:, 1:].flat:
     360                ax.yaxis.set_tick_params(which='both',
     361                                         labelleft=False, labelright=False)
     362                ax.yaxis.offsetText.set_visible(False)
     363
     364        if squeeze:
     365            # Discarding unneeded dimensions that equal 1.  If we only have one
     366            # subplot, just return it instead of a 1-element array.
     367            return axarr.item() if axarr.size == 1 else axarr.squeeze()
     368        else:
     369            # Returned axis array will be always 2-d, even if nrows=ncols=1.
     370            return axarr
     371
    249372class _tabPlotWin(wx.Panel):   
    250373    'Creates a basic tabbed plot window for GSAS-II graphics'
     
    429552                Plot = Page.figure.gca()          #get previous plot
    430553                limits = [Plot.get_xlim(),Plot.get_ylim()] # save previous limits
    431                 #======================================================================
    432                 # this is needed for PWDR (etc) "w" plots, but breaks image plotting
    433                 # removed for now (BHT)
    434                 #if len(Axes)>1:
    435                 #    limits[1] = Axes[1].get_ylim()
    436                 #======================================================================
    437 #                    print('Axes[1]',Axes[1].get_ylim())
    438 #                print ('Plot limits:',limits,Axes)
     554                if len(Axes)>1 and Plot.get_aspect() == 'auto':  # aspect will be equal for image plotting
     555                    limits[1] = Axes[1].get_ylim()
    439556                if newImage:
    440557                    Page.figure.clf()
     
    23632480        Plot.tick_params('y',length=0,labelleft=False)
    23642481        GS_kw = {'height_ratios':[4, 1],}
    2365         Plot,Plot1 = Page.figure.subplots(2,1,sharex=True,gridspec_kw=GS_kw)
     2482        try:
     2483            Plot,Plot1 = Page.figure.subplots(2,1,sharex=True,gridspec_kw=GS_kw)
     2484        except AttributeError: # figure.Figure.subplots added in MPL 2.2
     2485            Plot,Plot1 = MPLsubplots(Page.figure, 2, 1, sharex=True, gridspec_kw=GS_kw)
    23662486        Plot1.set_ylabel(r'$\mathsf{\Delta(I)/\sigma(I)}$',fontsize=16)
    23672487        Plot1.set_xlabel(xLabel,fontsize=16)
Note: See TracChangeset for help on using the changeset viewer.