def _genplot(ts, xlabel, ylabel, title, **pltkwargs): ''' Generic wrapper to ts.plot(), that takes in x/y/title as parsed from various calling functions.''' ### Add custom legend interface. Keyword legstyle does custom ones, if pltkwrd legend==True ### For now this could use improvement pltkwargs['legend']=pltkwargs.pop('legend', False) legstyle=pltkwargs.pop('legstyle', None) ### Make sure don't have "colors", or that 'colors' is not set to default if 'colors' in pltkwargs: if pltkwargs['color'].lower()=='default': pltkwargs.pop('color') if 'colors' in pltkwargs: pltkwargs['color']=pltkwargs.pop('colors') print 'Warning: in _genplot, overwriting kwarg "colors" to "color"' ax=ts.plot(**pltkwargs) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) if legstyle and pltkwargs['legend']==True: #Defaults to false if legstyle==0: ax.legend(loc='upper center', ncol=8, shadow=True, fancybox=True) #If l if legstyle==1: ax.legend(loc='upper left', ncol=2, shadow=True, fancybox=True) #If l if legstyle==2: ax=easy_legend(ax, position='top', fancy=True) return ax
def _genplot(ts, *args, **pltkwargs): """ Generic wrapper to ts._frame.plot(), that takes in x/y/title as parsed from various calling functions: NEW KEYWORDS: grid color labelsize titlesize ticksize xlim/ylabel cbar ax fig xlabel ylabel title legprefix and legend as integers - setting legprefix and not legend defaults legend to True """ # Add custom legend interface. # For now this could use improvement xlabel = pltkwargs.pop('xlabel', '') ylabel = pltkwargs.pop('ylabel', '') title = pltkwargs.pop('title', '') pltkwargs.setdefault('linewidth', 1) # Legend can be T/F, integer for pre-loaded styles legend = pltkwargs.setdefault('legend', False) legprefix = pltkwargs.pop('legprefix', None) # Adhere to cananoical "cmap" if 'cmap' in pltkwargs: pltkwargs['colormap'] = pltkwargs.pop('cmap') fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) cbar = pltkwargs.pop('cbar', False) _barlabels = 5 #Number of ticks/labels in colorbar xlim = pltkwargs.pop('xlim', None) ylim = pltkwargs.pop('ylim', None) custompadding = pltkwargs.pop('custompadding', 0.05) if not ax: f, ax = plt.subplots(1) if not fig: fig = f # Grid (add support for minor grids later) grid = pltkwargs.pop('grid', 'black') labelsize = pltkwargs.pop('labelsize', pvcnfg.LABELSIZE) #Can also be ints titlesize = pltkwargs.pop('titlesize', pvcnfg.TITLESIZE) ticksize = pltkwargs.pop('ticksize', '') #Put in default and remove bool gate below pltkwargs['ax'] = ax ax = ts._frame.plot(**pltkwargs) if cbar: if pltkwargs.get('color', None): raise PlotError('Colorbar requires cmap; solid color \ "%s" found.' % pltkwargs['color']) c_rotation, c_reverse = 90, False if cbar in ['r', 'reverse']: c_rotation, c_reverse = 270, True if not fig: raise PlotError("Color bar requries access to Figure. Either pass fig" " keyword or do not pass custom AxesSubplot.") # Need a colormap if you have a colorbar! try: pcmap = pltkwargs['colormap'] except KeyError: raise PlotError('Cannot plot a colorbar without a colormap!') mappable, vmin, vmax = put._annotate_mappable(ts, pcmap, axis=0) cbar = fig.colorbar(mappable, ticks=np.linspace(vmin, vmax, _barlabels)) tunit = pvutils.safe_lookup(ts, 'full_varunit') cbar.set_label(r'%s$\rightarrow$' % tunit, rotation=c_rotation) if len(ts.columns) > _barlabels -1: label_indices = np.linspace(0, len(ts.columns), _barlabels) label_indices = [int(round(x)) for x in label_indices] if label_indices[-1] > len(ts.columns)-1: label_indices[-1] = len(ts.columns)-1 #Rounds over max labels = [ts.columns[x] for x in label_indices] # IF LABELS ARE FLOATS (NEED A BETTER CONDITION THAN THIS) try: labels = [round(float(x),put.float_display_units) for x in label_indices] except Exception: pass # Don't add custom labels if aren't at least 5 columns if DF else: labels = [] cbar.ax.set_yticklabels(labels) if c_reverse: cbar.ax.invert_yaxis() # Add minor ticks through tick parameters ax.minorticks_on() ax.set_xlabel(xlabel, fontsize=labelsize) ax.set_ylabel(ylabel, fontsize=labelsize) ax.set_title(title, fontsize=titlesize) # Not normazling padding correctly! def _correct_padding(xi,xf): """ Note, when making multiplots, this can be an issue and users will want to do padding=None """ dlt_x = xf-xi boundary = abs(dlt_x *custompadding) low_bound = xi-boundary high_bound = xf+boundary return (low_bound, high_bound) if not xlim and custompadding is not None: try: xlim = _correct_padding(min(ts.index), max(ts.index)) ax.set_xlim(xlim) # Padding not inferrable from string indicies like in time plots except Exception: pass if not ylim and custompadding is not None: try: ylim = _correct_padding(ts.min().min(), ts.max().max()) ax.set_ylim(ylim) except Exception: pass # Legend as integer doesn't persist if legprefix. IE legprefix makes entirely new legend # but legend as an integer is so unused, who cares if legend: pltkwargs['legend'] = True if isinstance(legend, int): if legend == 0: ax.legend(loc='upper center', ncol=8, shadow=True, fancybox=True) elif legend == 1: ax.legend(loc='upper left', ncol=2, shadow=True, fancybox=True) elif legend == 2: ax=put.easy_legend(ax, position='top', fancy=True) if legprefix: if not isinstance(legprefix, basestring): raise PlotError('Plot keyword "legprefix" must be a string, got %s' % type(legprefix)) handles, labels = ax.get_legend_handles_labels() newlabels = ['%s%s' % (legprefix, i) for i in range(len(labels))] #step1, step2 etc... ax.legend(handles, newlabels) # http://matplotlib.org/api/axis_api.html # Other grid args like linestyle should be set directly with calls # to ax.grid(**linekwds) if grid: if grid == True: ax.grid() else: ax.grid(color=grid) #Let's any supported color in if ticksize: logger.info('Adjusting ticksize to "%s"' % ticksize) # Get all x and y ticks in a list allticks = ax.xaxis.get_majorticklabels() allticks.extend( ax.yaxis.get_majorticklabels() ) for label in allticks: label.set_fontsize(ticksize) # label.set_fontname('courier') return ax
def _genplot(ts, *args, **pltkwargs): """ Generic wrapper to ts._frame.plot(), that takes in x/y/title as parsed from various calling functions. Implements several new keyword parameters. Parameters ---------- ax : Matplotlib Axes Pass in an axes to add lines. If none, one is generated. color : str, int, or rgb Plot color ('r', (1,0,0), (128)). cbar : bool (False) Add colorbar to plot if colormap (cmap keyword) Returns: -------- ax : Matplotlib Axes grid NEW KEYWORDS: grid color labelsize titlesize ticksize xlim/ylabel cbar ax fig xlabel ylabel title legprefix and legend as integers - setting legprefix and not legend defaults legend to True """ # Add custom legend interface. # For now this could use improvement xlabel = pltkwargs.pop('xlabel', '') ylabel = pltkwargs.pop('ylabel', '') title = pltkwargs.pop('title', '') pltkwargs.setdefault('linewidth', 1) # Legend can be T/F, integer for pre-loaded styles legend = pltkwargs.setdefault('legend', False) legprefix = pltkwargs.pop('legprefix', None) # Adhere to cananoical "cmap" if 'cmap' in pltkwargs: pltkwargs['colormap'] = pltkwargs.pop('cmap') fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) cbar = pltkwargs.pop('cbar', False) _barlabels = 5 #Number of ticks/labels in colorbar xlim = pltkwargs.pop('xlim', None) ylim = pltkwargs.pop('ylim', None) custompadding = pltkwargs.pop('custompadding', 0.05) if not ax: f, ax = plt.subplots(1) if not fig: fig = f # Grid (add support for minor grids later) grid = pltkwargs.pop('grid', 'black') labelsize = pltkwargs.pop('labelsize', pvcnfg.LABELSIZE) #Can also be ints titlesize = pltkwargs.pop('titlesize', pvcnfg.TITLESIZE) ticksize = pltkwargs.pop('ticksize', '') #Put in default and remove bool gate below pltkwargs['ax'] = ax ax = ts._frame.plot(**pltkwargs) if cbar: if pltkwargs.get('color', None): raise PlotError('Colorbar requires cmap; solid color \ "%s" found.' % pltkwargs['color']) c_rotation, c_reverse = 90, False if cbar in ['r', 'reverse']: c_rotation, c_reverse = 270, True if not fig: raise PlotError( "Color bar requries access to Figure. Either pass fig" " keyword or do not pass custom AxesSubplot.") # Need a colormap if you have a colorbar! try: pcmap = pltkwargs['colormap'] except KeyError: raise PlotError('Cannot plot a colorbar without a colormap!') mappable, vmin, vmax = put._annotate_mappable(ts, pcmap, axis=0) cbar = fig.colorbar(mappable, ticks=np.linspace(vmin, vmax, _barlabels)) tunit = pvutils.safe_lookup(ts, 'full_varunit') cbar.set_label(r'%s$\rightarrow$' % tunit, rotation=c_rotation) if len(ts.columns) > _barlabels - 1: label_indices = np.linspace(0, len(ts.columns), _barlabels) label_indices = [int(round(x)) for x in label_indices] if label_indices[-1] > len(ts.columns) - 1: label_indices[-1] = len(ts.columns) - 1 #Rounds over max labels = [ts.columns[x] for x in label_indices] # IF LABELS ARE FLOATS (NEED A BETTER CONDITION THAN THIS) try: labels = [ round(float(x), put.float_display_units) for x in label_indices ] except Exception: pass # Don't add custom labels if aren't at least 5 columns if DF else: labels = [] cbar.ax.set_yticklabels(labels) if c_reverse: cbar.ax.invert_yaxis() # Add minor ticks through tick parameters ax.minorticks_on() ax.set_xlabel(xlabel, fontsize=labelsize) ax.set_ylabel(ylabel, fontsize=labelsize) ax.set_title(title, fontsize=titlesize) # Not normazling padding correctly! def _correct_padding(xi, xf): """ Note, when making multiplots, this can be an issue and users will want to do padding=None """ dlt_x = xf - xi boundary = abs(dlt_x * custompadding) low_bound = xi - boundary high_bound = xf + boundary return (low_bound, high_bound) if not xlim and custompadding is not None: try: xlim = _correct_padding(min(ts.index), max(ts.index)) ax.set_xlim(xlim) # Padding not inferrable from string indicies like in time plots except Exception: pass if not ylim and custompadding is not None: try: ylim = _correct_padding(ts.min().min(), ts.max().max()) ax.set_ylim(ylim) except Exception: pass # Legend as integer doesn't persist if legprefix. IE legprefix makes entirely new legend # but legend as an integer is so unused, who cares if legend: pltkwargs['legend'] = True if isinstance(legend, int): if legend == 0: ax.legend(loc='upper center', ncol=8, shadow=True, fancybox=True) elif legend == 1: ax.legend(loc='upper left', ncol=2, shadow=True, fancybox=True) elif legend == 2: ax = put.easy_legend(ax, position='top', fancy=True) if legprefix: if not isinstance(legprefix, basestring): raise PlotError( 'Plot keyword "legprefix" must be a string, got %s' % type(legprefix)) handles, labels = ax.get_legend_handles_labels() newlabels = [ '%s%s = %s' % (legprefix, i, labels[i]) for i, label in enumerate(labels) ] #step1, step2 etc... ax.legend(handles, newlabels) # http://matplotlib.org/api/axis_api.html # Other grid args like linestyle should be set directly with calls # to ax.grid(**linekwds) if grid: if grid == True: ax.grid() else: ax.grid(color=grid) #Let's any supported color in if ticksize: logger.info('Adjusting ticksize to "%s"' % ticksize) # Get all x and y ticks in a list allticks = ax.xaxis.get_majorticklabels() allticks.extend(ax.yaxis.get_majorticklabels()) for label in allticks: label.set_fontsize(ticksize) # label.set_fontname('courier') return ax
def _genplot(ts, *args, **pltkwargs): """ Generic wrapper to ts._frame.plot(), that takes in x/y/title as parsed from various calling functions: NEW KEYWORDS: grid color labelsize titlesize ticksize xlim/ylabel cbar ax fig xlabel ylabel title """ # Add custom legend interface. Keyword legstyle does custom ones, if pltkwrd legend==True # For now this could use improvement xlabel = pltkwargs.pop('xlabel', '') ylabel = pltkwargs.pop('ylabel', '') title = pltkwargs.pop('title', '') pltkwargs.setdefault('legend', False) pltkwargs.setdefault('linewidth', 1) legstyle = pltkwargs.pop('legstyle', None) # Adhere to cananoical "cmap" if 'cmap' in pltkwargs: pltkwargs['colormap'] = pltkwargs.pop('cmap') pcmap = pltkwargs.setdefault('colormap', 'jet') fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) cbar = pltkwargs.pop('cbar', False) _barlabels = 5 #Number of ticks/labels in colorbar xlim = pltkwargs.pop('xlim', None) ylim = pltkwargs.pop('ylim', None) custompadding = pltkwargs.pop('custompadding', 0.05) if not ax: f, ax = plt.subplots(1) if not fig: fig = f # Grid (add support for minor grids later) grid = pltkwargs.pop('grid', True) labelsize = pltkwargs.pop('labelsize', 'medium') #Can also be ints titlesize = pltkwargs.pop('titlesize', 'large') ticksize = pltkwargs.pop('ticksize', '') #Put in default and remove bool gate below pltkwargs['ax'] = ax ax = ts._frame.plot(**pltkwargs) if cbar: if 'color' in pltkwargs: raise PlotError('Colorbar requires cmap; solid color \ "%s" found.' % pltkwargs['color']) c_rotation, c_reverse = 90, False if cbar in ['r', 'reverse']: c_rotation, c_reverse = 270, True if not fig: raise PlotError("Color bar requries access to Figure. Either pass fig" " keyword or do not pass custom AxesSubplot.") mappable, vmin, vmax = put._annotate_mappable(ts, pcmap, axis=0) cbar = fig.colorbar(mappable, ticks=np.linspace(vmin, vmax, _barlabels)) tunit = getattr(ts, 'full_varunit', 'Perturbation') cbar.set_label(r'%s$\rightarrow$' % tunit, rotation=c_rotation) if len(ts.columns) > _barlabels -1: label_indices = np.linspace(0, len(ts.columns), _barlabels) label_indices = [int(round(x)) for x in label_indices] if label_indices[-1] > len(ts.columns)-1: label_indices[-1] = len(ts.columns)-1 #Rounds over max labels = [ts.columns[x] for x in label_indices] if getattr(ts, '_intervalunit', None): if ts._interval and ts._intervalunit != 'intvl': labels = [round(float(x),puc.float_display_units) for x in label_indices] # Don't add custom labels if aren't at least 5 columns if DF else: labels = [] cbar.ax.set_yticklabels(labels) if c_reverse: cbar.ax.invert_yaxis() # Add minor ticks through tick parameters ax.minorticks_on() ax.set_xlabel(xlabel, fontsize=labelsize) ax.set_ylabel(ylabel, fontsize=labelsize) ax.set_title(title, fontsize=titlesize) # Not normazling padding correctly! def _correct_padding(xi,xf): """ Note, when making multiplots, this can be an issue and users will want to do padding=None """ dlt_x = xf-xi boundary = abs(dlt_x *custompadding) low_bound = xi-boundary high_bound = xf+boundary return (low_bound, high_bound) if not xlim and custompadding is not None: try: xlim = _correct_padding(min(ts.index), max(ts.index)) ax.set_xlim(xlim) # Padding not inferrable from string indicies like in time plots except Exception: pass if not ylim and custompadding is not None: try: ylim = _correct_padding(ts.min().min(), ts.max().max()) ax.set_ylim(ylim) except Exception: pass if legstyle and pltkwargs['legend'] == True: #Defaults to False if legstyle == 0: ax.legend(loc='upper center', ncol=8, shadow=True, fancybox=True) elif legstyle == 1: ax.legend(loc='upper left', ncol=2, shadow=True, fancybox=True) elif legstyle == 2: ax=put.easy_legend(ax, position='top', fancy=True) if grid: ax.grid(True) if ticksize: logger.info('Adjusting ticksize to "%s"' % ticksize) # Get all x and y ticks in a list allticks = ax.xaxis.get_majorticklabels() allticks.extend( ax.yaxis.get_majorticklabels() ) for label in allticks: label.set_fontsize(ticksize) # label.set_fontname('courier') return ax
def _genplot(ts, **pltkwargs): """ Generic wrapper to ts._df.plot(), that takes in x/y/title as parsed from various calling functions: NEW KEYWORDS: grid color labelsize titlesize ticksize xlim/ylabel cbar ax fig xlabel ylabel title """ # Add custom legend interface. Keyword legstyle does custom ones, if pltkwrd legend==True # For now this could use improvement xlabel = pltkwargs.pop('xlabel', '') ylabel = pltkwargs.pop('ylabel', '') title = pltkwargs.pop('title', '') pltkwargs.setdefault('legend', False) pltkwargs.setdefault('linewidth', 1) legstyle = pltkwargs.pop('legstyle', None) pcmap = pltkwargs.setdefault('colormap', 'jet') fig = pltkwargs.pop('fig', None) ax = pltkwargs.pop('ax', None) cbar = pltkwargs.pop('cbar', False) _barlabels = 5 #Number of ticks/labels in colorbar xlim = pltkwargs.pop('xlim', None) ylim = pltkwargs.pop('ylim', None) custompadding = pltkwargs.pop('custompadding', 0.05) if not ax: f, ax = plt.subplots(1) if not fig: fig = f # Grid (add support for minor grids later) grid = pltkwargs.pop('grid', True) labelsize = pltkwargs.pop('labelsize', 'medium') #Can also be ints titlesize = pltkwargs.pop('titlesize', 'large') ticksize = pltkwargs.pop('ticksize', '') #Put in default and remove bool gate below pltkwargs['ax'] = ax ax = ts._df.plot(**pltkwargs) if cbar: if 'color' in pltkwargs: raise PlotError('Colorbar requires colormap; solid color \ "%s" found.' % pltkwargs['color']) c_rotation, c_reverse = 90, False if cbar in ['r', 'reverse']: c_rotation, c_reverse = 270, True if not fig: raise PlotError("Color bar requries access to Figure. Either pass fig" " keyword or do not pass custom AxesSubplot.") mappable, vmin, vmax = put._annotate_mappable(ts, pcmap, axis=0) cbar = fig.colorbar(mappable, ticks=np.linspace(vmin, vmax, _barlabels)) tunit = getattr(ts, 'full_varunit', 'Perturbation') cbar.set_label(r'%s$\rightarrow$' % tunit, rotation=c_rotation) if len(ts.columns) > _barlabels -1: label_indices = np.linspace(0, len(ts.columns), _barlabels) label_indices = [int(round(x)) for x in label_indices] if label_indices[-1] > len(ts.columns)-1: label_indices[-1] = len(ts.columns)-1 #Rounds over max labels = [ts.columns[x] for x in label_indices] if getattr(ts, '_intervalunit', None): if ts._interval and ts._intervalunit != 'intvl': labels = [round(float(x),puc.float_display_units) for x in label_indices] # Don't add custom labels if aren't at least 5 columns if DF else: labels = [] cbar.ax.set_yticklabels(labels) if c_reverse: cbar.ax.invert_yaxis() # Add minor ticks through tick parameters ax.minorticks_on() ax.set_xlabel(xlabel, fontsize=labelsize) ax.set_ylabel(ylabel, fontsize=labelsize) ax.set_title(title, fontsize=titlesize) # Not normazling padding correctly! def _correct_padding(xi,xf): """ Note, when making multiplots, this can be an issue and users will want to do padding=None """ dlt_x = xf-xi boundary = abs(dlt_x *custompadding) low_bound = xi-boundary high_bound = xf+boundary return (low_bound, high_bound) if not xlim and custompadding is not None: try: xlim = _correct_padding(min(ts.index), max(ts.index)) ax.set_xlim(xlim) # Padding not inferrable from string indicies like in time plots except Exception: pass if not ylim and custompadding is not None: try: ylim = _correct_padding(ts.min().min(), ts.max().max()) ax.set_ylim(ylim) except Exception: pass if legstyle and pltkwargs['legend'] == True: #Defaults to False if legstyle == 0: ax.legend(loc='upper center', ncol=8, shadow=True, fancybox=True) elif legstyle == 1: ax.legend(loc='upper left', ncol=2, shadow=True, fancybox=True) elif legstyle == 2: ax=put.easy_legend(ax, position='top', fancy=True) if grid: ax.grid(True) if ticksize: logger.info('Adjusting ticksize to "%s"' % ticksize) # Get all x and y ticks in a list allticks = ax.xaxis.get_majorticklabels() allticks.extend( ax.yaxis.get_majorticklabels() ) for label in allticks: label.set_fontsize(ticksize) # label.set_fontname('courier') return ax