Changeset 17778


Ignore:
Timestamp:
04/18/14 17:10:05 (11 years ago)
Author:
cborstad
Message:

CHG: better handling of multiple subplots in python plotmodel, now uses matplotlib's AxesGrid toolkit to specify the axes grid at the beginning of plotting; this ensures better handling of things like aspect ratios, colorbars, and spacing between plots

Location:
issm/trunk-jpl/src/m/plot
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/plot/applyoptions.py

    r17756 r17778  
    88        import matplotlib as mpl
    99        import pylab as p
     10        import matplotlib.pyplot as plt
    1011except ImportError:
    1112        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
    1213
    13 def applyoptions(md,data,options):
     14def applyoptions(md,data,options,fig,ax):
    1415        '''
    1516        APPLYOPTIONS - apply options to current plot
     17
     18        'plotobj' is the object returned by the specific plot call used to
     19        render the data.  This object is used for adding a colorbar.
    1620
    1721                Usage:
     
    2630
    2731        # get handle to current figure and axes instance
    28         fig = p.gcf()
    29         ax=p.gca()
     32        #fig = p.gcf()
     33        #ax=p.gca()
    3034
    3135        #font {{{
    32         fontsize=options.getfieldvalue('fontsize',14)
     36        fontsize=options.getfieldvalue('fontsize',8)
    3337        fontweight=options.getfieldvalue('fontweight','normal')
    3438        fontfamily=options.getfieldvalue('fontfamily','sans-serif')
     
    5559                titlefont['size']=titlefontsize
    5660                titlefont['weight']=titlefontweight
    57                 p.title(title,**titlefont)
     61                fig.set_title(title,**titlefont)
    5862        #}}}
    5963               
     
    7478
    7579        if options.exist('xlabel'):
    76                 p.xlabel(options.getfieldvalue('xlabel'),**labelfont)
     80                ax.set_xlabel(options.getfieldvalue('xlabel'),**labelfont)
    7781        if options.exist('ylabel'):
    78                 p.ylabel(options.getfieldvalue('ylabel'),**labelfont)
     82                ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont)
    7983        if options.exist('zlabel'):
    80                 p.zlabel(options.getfieldvalue('zlabel'),**labelfont)
     84                ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont)
    8185        #}}}
    8286
     
    8589                if options.exist('xticklabels'):
    8690                        xticklabels=options.getfieldvalue('xticklabels')
    87                         p.xticks(options.getfieldvalue('xticks'),xticklabels)
    88                 else:
    89                         p.xticks(options.getfieldvalue('xticks'))
     91                        ax.set_xticks(options.getfieldvalue('xticks'),xticklabels)
     92                else:
     93                        ax.set_xticks(options.getfieldvalue('xticks'))
    9094        if options.exist('yticks'):
    9195                if options.exist('yticklabels'):
    9296                        yticklabels=options.getfieldvalue('yticklabels')
    93                         p.yticks(options.getfieldvalue('yticks'),yticklabels)
    94                 else:
    95                         p.yticks(options.getfieldvalue('yticks'))
     97                        ax.set_yticks(options.getfieldvalue('yticks'),yticklabels)
     98                else:
     99                        ax.set_yticks(options.getfieldvalue('yticks'))
    96100        if options.exist('zticks'):
    97101                if options.exist('zticklabels'):
    98102                        zticklabels=options.getfieldvalue('zticklabels')
    99                         p.zticks(options.getfieldvalue('zticks'),zticklabels)
    100                 else:
    101                         p.zticks(options.getfieldvalue('zticks'))
     103                        ax.set_zticks(options.getfieldvalue('zticks'),zticklabels)
     104                else:
     105                        ax.set_zticks(options.getfieldvalue('zticks'))
    102106        #}}}
    103107
     
    106110                xticklabels=options.getfieldvalue('xticklabels')
    107111                xtickloc=p.xticks()[0] 
    108                 p.xticks(xtickloc,xticklabels)
     112                ax.set_xticks(xtickloc,xticklabels)
    109113        if options.exist('yticklabels'):
    110114                yticklabels=options.getfieldvalue('yticklabels')
    111115                ytickloc=p.yticks()[0] 
    112                 p.yticks(ytickloc,yticklabels)
     116                ax.set_yticks(ytickloc,yticklabels)
    113117        if options.exist('zticklabels'):
    114118                zticklabels=options.getfieldvalue('zticklabels')
    115119                ztickloc=p.zticks()[0] 
    116                 p.zticks(ztickloc,zticklabels)
     120                ax.set_zticks(ztickloc,zticklabels)
    117121        #}}}
    118122
     
    144148        #xlim, ylim, zlim {{{
    145149        if options.exist('xlim'):
    146                 p.xlim(options.getfieldvalue('xlim'))
     150                ax.set_xlim(options.getfieldvalue('xlim'))
    147151        if options.exist('ylim'):
    148                 p.ylim(options.getfieldvalue('ylim'))
     152                ax.set_ylim(options.getfieldvalue('ylim'))
    149153        if options.exist('zlim'):
    150                 p.zlim(options.getfieldvalue('zlim'))
     154                ax.set_zlim(options.getfieldvalue('zlim'))
    151155        #}}}
    152156
     
    174178        if options.exist('grid'):
    175179                if 'on' in options.getfieldvalue('grid','on'):
    176                         p.grid()
     180                        ax.grid()
    177181        #}}}
    178182
     
    195199        #}}}
    196200
     201        #contours {{{
     202        if options.exist('contourlevels'):
     203                plot_contour(md,data,options,ax)
     204        #}}}
     205
    197206        #wrapping
    198207
    199208        #colorbar {{{
    200209        if options.getfieldvalue('colorbar',1)==1:
    201                 divider = make_axes_locatable(ax)
    202                 cax = divider.new_horizontal("5%", pad=0.05, axes_class=mpl.axes.Axes)
    203                 fig.add_axes(cax)
    204210                if cbar_extend==0:
    205211                        extend='neither'
     
    210216                elif cbar_extend==3:
    211217                        extend='both'
    212                 cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, extend=extend)
     218                cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
    213219                cb.locator=MaxNLocator(nbins=5) # default 5 ticks
    214                 cb.update_ticks()
     220                if options.exist('alpha'):
     221                        cb.set_alpha(options.getfieldvalue('alpha'))
    215222                if options.exist('colorbarnumticks'):
    216223                        cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
    217                         cb.update_ticks()
     224                if options.exist('colorbartickspacing'):
     225                        locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
     226                        cb.set_ticks(locs)
     227                if options.exist('colorbarlines'):
     228                        locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines'))
     229                        cb.add_lines(locs,['k' for i in range(len(locs))],npy.ones_like(locs))
     230                if options.exist('colorbartitle'):
     231                        cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
     232                cb.ax.tick_params(labelsize=fontsize)
    218233        #}}}
    219234
     
    230245        #streamlines
    231246
    232         #contours {{{
    233         if options.exist('contourlevels'):
    234                 plot_contour(md,data,options)
    235         #}}}
    236247
    237248        #axis positions
  • issm/trunk-jpl/src/m/plot/plot_contour.py

    r17756 r17778  
    44from processdata import processdata
    55
    6 def plot_contour(md,datain,options):
     6def plot_contour(md,datain,options,ax):
    77        '''
    88        plot contours of a given field (called within plotmodel)
     
    1616        x,y,z,elements,is2d,isplanet=processmesh(md,datain,options)
    1717        data,datatype=processdata(md,datain,options)
    18         ax=plt.gca()
    1918
    2019        # process data: must be on nodes
  • issm/trunk-jpl/src/m/plot/plot_manager.py

    r17756 r17778  
    11try:
    22        import pylab as p
     3        import matplotlib.pyplot as plt
    34except ImportError:
    45        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
     
    1213from plot_overlay import plot_overlay
    1314
    14 def plot_manager(md,options,subplotwidth,nlines,ncols,i):
     15def plot_manager(md,options,fig,ax):
    1516        '''
    1617        PLOT_MANAGER - distribute the plots called by plotmodel
    1718
    18                 Usage:
    19                         plot_manager(md,options,subplotwidth,i);
     19        'fig' is a handle to the figure instance created by plotmodel.
    2020
    21                 See also: PLOTMODEL, PLOT_UNIT
     21        'ax' is a handle to the axes instance created by plotmodel.  This is
     22        currently generated using matplotlib's AxesGrid toolki.
     23
     24        Usage:
     25                plot_manager(md,options,fig,ax);
     26
     27        See also: PLOTMODEL, PLOT_UNIT
    2228        '''
    2329
     
    2935
    3036        #initialize plot handle variable
    31         handle=None
     37        #handle=None
    3238
    3339        # initialize subplot
    34         p.subplot(nlines,ncols,i,aspect='equal')
     40        #p.subplot(nrows,ncols,i,aspect='equal')
    3541
    3642        ##basemap plot
    3743        #if options.exist('basemap'):
    38         #       plot_basemap(md,data,options,nlines,ncols,i)
     44        #       plot_basemap(md,data,options,nrows,ncols,i)
    3945
    4046        #overlay plot
    4147        if options.exist('overlay'):
    42                 handle=plot_overlay(md,data,options,nlines,ncols,i)
     48                plot_overlay(md,data,options,ax)
    4349                options.addfielddefault('alpha',0.5)
    4450                options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)])
     
    5056                # convert string to lower case for a case-insensitive comparison
    5157                if data.lower()=='mesh':
    52                         plot_mesh(md,options,nlines,ncols,i)
     58                        plot_mesh(md,options,ax)
    5359                        return
    5460                elif data.lower()=='none':
     
    7480        #standard plot
    7581        #if not handle:
    76         #       p.subplot(nlines,ncols,i,aspect='equal')
     82        #       p.subplot(nrows,ncols,i,aspect='equal')
    7783
    7884        #plot unit
    79         plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options)
     85        plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)
    8086
    8187        #apply all options
    82         applyoptions(md,data2,options)
     88        applyoptions(md,data2,options,fig,ax)
    8389       
    8490        #ground overlay on kml plot_unit
  • issm/trunk-jpl/src/m/plot/plot_overlay.py

    r17756 r17778  
    77import os
    88
    9 def plot_overlay(md,data,options,rows,cols,i):
     9def plot_overlay(md,data,options,ax):
    1010        '''
    1111        Function for plotting a georeferenced image.  This function is called
     
    7676                plt.sca(ax) # return to original axes/figure
    7777               
    78 
    7978        # get parameters from cropped geotiff
    8079        trans=gtif.GetGeoTransform()
     
    9089        xg,yg=npy.meshgrid(xarr,yarr)
    9190        if options.exist('basemap'):
    92                 # TODO get handle to basemap instance
    93                 # handle= functiontogethandle()
     91                # TODO get handle to or create basemap instance
    9492                # create coordinate grid in map projection units (for plotting)
    9593                lats,lons=xy2ll(xg,yg,-1,0,71)
     
    9896                xgmap=xg
    9997                ygmap=yg
    100                 handle=plt.gca()
    10198       
    10299        overlaylims=options.getfieldvalue('overlaylims',[min(arr.ravel()),max(arr.ravel())])
     
    104101        norm=mpl.colors.Normalize(vmin=overlaylims[0],vmax=overlaylims[1])
    105102
    106         handle.pcolormesh(xgmap, ygmap, npy.flipud(arr), cmap=mpl.cm.Greys, norm=norm)
    107         handle.set_aspect('equal','box')
    108         return handle
     103        ax.pcolormesh(xgmap, ygmap, npy.flipud(arr), cmap=mpl.cm.Greys, norm=norm)
  • issm/trunk-jpl/src/m/plot/plot_unit.py

    r17716 r17778  
    33        import pylab as p
    44        import matplotlib as mpl
     5        import matplotlib.pyplot as plt
    56except ImportError:
    67        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
    78
    8 def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options):
     9def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,ax):
    910        """
    1011        PLOT_UNIT - unit plot, display data
     
    4647           #element plot
    4748                if is2d:
    48                         p.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,edgecolors=edgecolor)
     49                        tri=ax.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,edgecolors=edgecolor)
    4950                else:
    5051                        raise ValueError('plot_unit error: 3D element plot not supported yet')
    51                 return
     52                return 
    5253       
    5354        elif datatype==2:
    5455                #node plot
    5556                if is2d:
    56                         p.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
     57                        tri=ax.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
    5758                        if edgecolor != 'None':
    58                                 p.triplot(x,y,elements,color=edgecolor)
     59                                ax.triplot(x,y,elements,color=edgecolor)
    5960                else:
    6061                        raise ValueError('plot_unit error: 3D node plot not supported yet')
     
    7677        else:
    7778                raise ValueError('datatype=%d not supported' % datatype)
     79
  • issm/trunk-jpl/src/m/plot/plotmodel.py

    r17756 r17778  
    44try:
    55        import pylab as p
     6        import matplotlib.pyplot as plt
     7        from mpl_toolkits.axes_grid1 import ImageGrid
    68except ImportError:
    79        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
     
    2830        hold=options.list[0].getfieldvalue('hold',False)
    2931
    30         #if nlines and ncols specified, then bypass
    31         if options.list[0].exist('nlines'):
    32                 nlines=options.list[0].getfieldvalue('nlines')
    33                 nl=True
     32        #if nrows and ncols specified, then bypass
     33        if options.list[0].exist('nrows'):
     34                nrows=options.list[0].getfieldvalue('nrows')
     35                nr=True
    3436        else:
    35                 nlines=npy.ceil(numberofplots/subplotwidth)
    36                 nl=False
     37                nrows=npy.ceil(numberofplots/subplotwidth)
     38                nr=False
    3739       
    3840        if options.list[0].exist('ncols'):
     
    4345                nc=False
    4446       
    45         #check that nlines and ncols were given at the same time!
    46         if not nl==nc:
    47                 raise StandardError('error: nlines and ncols need to be specified together, or not at all')
     47        #check that nrows and ncols were given at the same time!
     48        if not nr==nc:
     49                raise StandardError('error: nrows and ncols need to be specified together, or not at all')
    4850       
    4951        #Go through plots
    5052        if numberofplots:
    5153               
    52                 #Create figure
    53                 #plots will be visible by default if ipython is run in interactive mode (invoked by ipython --pylab)
    54                 #UNLESS plotmodel is called within a script (e.g. a runme.py file)
    55                 #handling the 'visible' option will need some check on whether ipython is currently in interactive or non-interactive mode
     54                if not hold: # TODO need to also check whether figurenumber is a new plot so that old plots are not mistakenly cleared
     55                        plt.cla()
    5656
    57                 if not hold: # TODO need to also check whether figurenumber is a new plot so that old plots are not mistakenly cleared
    58                         p.cla()
    59 
    60                 #TODO fig, axarray = plt.subplots(nrows,ncols), then pass fix and axarr to plot_manager
    6157                #if figsize specified
    6258                if options.list[0].exist('figsize'):
    6359                        figsize=options.list[0].getfieldvalue('figsize')
    64                         p.figure(figurenumber,figsize=figsize)
     60                        fig=plt.figure(figurenumber,figsize=figsize,tight_layout=True)
    6561                else:
    66                         p.figure(figurenumber)
    67                        
    68                 #try:
     62                        fig=plt.figure(figurenumber,tight_layout=True)
     63                fig.clf()
     64       
     65                # options to pass: axes_pad, share_all, label_mode ("1","L","all"), cbar_mode (none,single,each), cbar_location(right,top)
     66                axgrid=ImageGrid(fig, 111,
     67                                nrows_ncols=(nrows,ncols),
     68                                direction='row',
     69                                axes_pad=0.05,
     70                                add_all=True,
     71                                share_all=True,
     72                                label_mode='all',
     73                                cbar_mode='single',
     74                                cbar_location='right',
     75                                cbar_size='5%',
     76                                cbar_pad=0.05
     77                                )
     78
    6979                for i in xrange(numberofplots):
    70                         plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],subplotwidth,nlines,ncols,i+1)
    71                 #except StandardError:
    72                 #       print 'error in plot_manager'
    73                 p.show()
     80                        plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid[i])
     81
     82                plt.show()
    7483        else:
    7584                raise StandardError('plotmodel error message: no output data found.')
Note: See TracChangeset for help on using the changeset viewer.