def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''): '''format 2d-plot black and with with times legends ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() font.set_name('Script MT') font.set_family('serif') font.set_style('normal') # font.set_size('small') font.set_size('large') font.set_variant('normal') font.set_weight('medium') if xlim != None and ylim != None: axes.axis([0, xlim, 0., ylim], fontproperties=font) # format ticks for plot # locs, labels = axes.xticks() axes.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) axes.xlabel(xlabel, fontproperties=font) locs, labels = axes.yticks() axes.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) axes.ylabel(ylabel, fontproperties=font)
def _check_font_properties(self, font0, weight='normal'): ''' Check if the given font properties are valid. ''' # font = self._get_dict(font0) # fontp = FontProperties() # 6 parameters in a font properties dictionary vkey = ['family', 'style', 'variant', 'stretch', 'weight', 'size'] for k in font: if k not in vkey: return fontp # if k == 'style': if not font[k] in self.fstyle: font[k] = 'normal' else: font['style'] = 'normal' if k == 'variant': if not font[k] in self.fvariant: font[k] = 'normal' else: font['variant'] = 'normal' if k == 'stretch': if not isfloat(font[k]): if font[k] not in self.fstretch: font[k] = 'normal' else: if not (0. < float(font[k]) < 1000.): font[k] = 'normal' else: font['stretch'] = 'normal' if k == 'weight': if not isfloat(font[k]): if font[k] not in self.fweight: font[k] = weight else: if not (0. < float(font[k]) < 1000.): font[k] = weight else: font['weight'] = weight if k == 'size': if not isfloat(font[k]): if font[k] not in self.fsize: font[k] = 12. else: if not (0. < float(font[k]) < 100.): font[k] = 12. else: font['size'] = 12. # fontp.set_family(font['family']) fontp.set_size(font['size']) fontp.set_weight(font['weight']) fontp.set_variant(font['variant']) fontp.set_stretch(font['stretch']) fontp.set_style(font['style']) # return fontp
def font_properties_from_style(style: dict) -> FontProperties: """ convert a style to a FontProperties object """ fp = FontProperties() for key, value in style.items(): if key == "font-family": fp.set_family(value) if key == "font-size": fp.set_size(svgUnitToMpl(value)) if key == "font-weight": fp.set_weight(value) if key == "font-style": fp.set_style(value) if key == "font-variant": fp.set_variant(value) if key == "font-stretch": fp.set_stretch(value) return fp
def font_properties_from_style(style): from matplotlib.font_manager import FontProperties fp = FontProperties() for key, value in style.items(): if key == "font-family": fp.set_family(value) if key == "font-size": fp.set_size(svgUnitToMpl(value)) if key == "font-weight": fp.set_weight(value) if key == "font-style": fp.set_style(value) if key == "font-variant": fp.set_variant(value) if key == "font-stretch": fp.set_stretch(value) return fp
class TickLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Save plotting parameters (required for @auto_refresh) self._parameters = parent._parameters # Set font self._label_fontproperties = FontProperties() self.set_style("plain") system, equinox, units = wcs_util.system(self._wcs) # Set default label format if self._wcs.xaxis_coord_type in ["longitude", "latitude"]: if system["name"] == "equatorial": if self._wcs.xaxis_coord_type == "longitude": self.set_xformat("hh:mm:ss.ss") else: self.set_xformat("dd:mm:ss.s") else: self.set_xformat("ddd.dddd") else: self.set_xformat("%g") if self._wcs.yaxis_coord_type in ["longitude", "latitude"]: if system["name"] == "equatorial": if self._wcs.yaxis_coord_type == "longitude": self.set_yformat("hh:mm:ss.ss") else: self.set_yformat("dd:mm:ss.s") else: self.set_yformat("ddd.dddd") else: self.set_yformat("%g") # Set major tick formatters fx1 = WCSFormatter(wcs=self._wcs, coord="x") fy1 = WCSFormatter(wcs=self._wcs, coord="y") self._ax1.xaxis.set_major_formatter(fx1) self._ax1.yaxis.set_major_formatter(fy1) fx2 = mpl.NullFormatter() fy2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) self._ax2.yaxis.set_major_formatter(fy2) # Cursor display self._ax1._cursor_world = True self._figure.canvas.mpl_connect("key_press_event", self._set_cursor_prefs) @auto_refresh def set_xformat(self, format): """ Set the format of the x-axis tick labels. If the x-axis type is ``longitude`` or ``latitude``, then the options are: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If the x-axis type is ``scalar``, then the format should be a valid python string format beginning with a ``%``. If one of these arguments is not specified, the format for that axis is left unchanged. """ if self._wcs.xaxis_coord_type in ["longitude", "latitude"]: if format.startswith("%"): raise Exception("Cannot specify Python format for longitude or latitude") try: if not self._ax1.xaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency(format, self._ax1.xaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return else: if not format.startswith("%"): raise Exception("For scalar tick labels, format should be a Python format beginning with %") self._ax1.xaxis.apl_label_form = format self._ax2.xaxis.apl_label_form = format @auto_refresh def set_yformat(self, format): """ Set the format of the y-axis tick labels. If the y-axis type is ``longitude`` or ``latitude``, then the options are: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If the y-axis type is ``scalar``, then the format should be a valid python string format beginning with a ``%``. If one of these arguments is not specified, the format for that axis is left unchanged. """ if self._wcs.yaxis_coord_type in ["longitude", "latitude"]: if format.startswith("%"): raise Exception("Cannot specify Python format for longitude or latitude") try: if not self._ax1.yaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency(format, self._ax1.yaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return else: if not format.startswith("%"): raise Exception("For scalar tick labels, format should be a Python format beginning with %") self._ax1.yaxis.apl_label_form = format self._ax2.yaxis.apl_label_form = format @auto_refresh def set_style(self, style): """ Set the format of the x-axis tick labels. This can be 'colons' or 'plain': * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1 * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1" """ if style == "latex": warnings.warn( "latex has now been merged with plain - whether or not to use LaTeX is controled through set_system_latex" ) style = "plain" if not style in ["colons", "plain"]: raise Exception("Label style should be one of colons/plain") self._ax1.xaxis.apl_labels_style = style self._ax1.yaxis.apl_labels_style = style self._ax2.xaxis.apl_labels_style = style self._ax2.yaxis.apl_labels_style = style @auto_refresh @fixdocstring def set_font( self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None ): """ Set the font of the tick labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties for tick in self._ax1.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax1.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis tick labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis tick labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(True) for tick in self._ax2.get_xticklabels(): tick.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(False) for tick in self._ax2.get_xticklabels(): tick.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(True) for tick in self._ax2.get_yticklabels(): tick.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(False) for tick in self._ax2.get_yticklabels(): tick.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis tick labels ('top' or 'bottom')" if position == "bottom": fx1 = WCSFormatter(wcs=self._wcs, coord="x") self._ax1.xaxis.set_major_formatter(fx1) fx2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) elif position == "top": fx1 = mpl.NullFormatter() self._ax1.xaxis.set_major_formatter(fx1) fx2 = WCSFormatter(wcs=self._wcs, coord="x") self._ax2.xaxis.set_major_formatter(fx2) else: raise ValueError("position should be one of 'top' or 'bottom'") @auto_refresh def set_yposition(self, position): "Set the position of the y-axis tick labels ('left' or 'right')" if position == "left": fy1 = WCSFormatter(wcs=self._wcs, coord="y") self._ax1.yaxis.set_major_formatter(fy1) fy2 = mpl.NullFormatter() self._ax2.yaxis.set_major_formatter(fy2) elif position == "right": fy1 = mpl.NullFormatter() self._ax1.yaxis.set_major_formatter(fy1) fy2 = WCSFormatter(wcs=self._wcs, coord="y") self._ax2.yaxis.set_major_formatter(fy2) else: raise ValueError("position should be one of 'left' or 'right'") def _set_cursor_prefs(self, event, **kwargs): if event.key == "c": self._ax1._cursor_world = not self._ax1._cursor_world def _cursor_position(self, x, y): xaxis = self._ax1.xaxis yaxis = self._ax1.yaxis if self._ax1._cursor_world: xw, yw = wcs_util.pix2world(self._wcs, x, y) if self._wcs.xaxis_coord_type in ["longitude", "latitude"]: xw = au.Angle(degrees=xw, latitude=self._wcs.xaxis_coord_type == "latitude") hours = "h" in xaxis.apl_label_form if hours: xw = xw.tohours() if xaxis.apl_labels_style in ["plain", "latex"]: sep = ("d", "m", "s") if hours: sep = ("h", "m", "s") elif xaxis.apl_labels_style == "colons": sep = (":", ":", "") xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep) xlabel = string.join(xlabel, "") else: xlabel = xaxis.apl_label_form % xw if self._wcs.yaxis_coord_type in ["longitude", "latitude"]: yw = au.Angle(degrees=yw, latitude=self._wcs.yaxis_coord_type == "latitude") hours = "h" in yaxis.apl_label_form if hours: yw = yw.tohours() if yaxis.apl_labels_style in ["plain", "latex"]: sep = ("d", "m", "s") if hours: sep = ("h", "m", "s") elif yaxis.apl_labels_style == "colons": sep = (":", ":", "") ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep) ylabel = string.join(ylabel, "") else: ylabel = yaxis.apl_label_form % yw return "%s %s (world)" % (xlabel, ylabel) else: return "%g %g (pixel)" % (x, y)
def plot_trial_steps(self): '''Plot target (sig-eps-curve of the tensile test) and trial curves and corresponding phi function together with trail steps from the iteration process. NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values within the global variables 'phi_trial_list_n' and 'sig_trial_list_n' n - index of the time steps to be considered i - index of the iteration steps performed in order to fit the target curve ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() # font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman # font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif # font.cursive : Zapf Chancery # font.monospace : Courier, Computer Modern Typewriter font.set_name('Script MT') # name = ['Times New Roman', 'Helvetica', 'Script MT'] #? font.set_family('serif') # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'] font.set_style('normal') # style = ['normal', 'italic', 'oblique'] font.set_size('small') # size = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11'] font.set_variant('normal') # variant= ['normal', 'small-caps'] font.set_weight('medium') # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] #------------------------------------------------------------------- p.figure(facecolor='white', dpi=600, figsize=(8, 6)) # white background # time list corresponding to the specified numbers of steps and step size # step_list = [n * self.step_size for n in range(self.n_steps + 1)] # get list of lists containing the trial values of 'sig_app' and 'phi_trail' # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled # within the iteration process when the method 'get_lack_of_fit" is called # phi_trial_list_n = [[1.]] + self.phi_trial_list_n sig_trial_list_n = [[0.]] + self.sig_trial_list_n xrange = 10. # plotting range for strain [mm/m] yrange = 15. # plotting range for stress [MPa] for n in range(self.n_steps): for i in range(len(phi_trial_list_n[n + 1])): x = np.array([step_list[n], step_list[n + 1]]) eps = 1000. * x # plot strains in permil on the x-axis #-------------------------------------- # sig-eps trial #-------------------------------------- # plot the numerically calculated sig-eps-curve (tensile test) # (with trial steps) # sig_trail = np.array( [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]]) p.subplot(222) p.plot(eps, sig_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange], fontproperties=font) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) #-------------------------------------- # phi_trail #-------------------------------------- # plot the fitted phi-function # (with trial steps) # p.subplot(224) phi_trail = np.array( [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]]) p.plot(eps, phi_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.1f" % x, locs), fontproperties=font) #-------------------------------------- # sig-eps target #-------------------------------------- # plot the sig-eps-target curve (tensile test) # p.subplot(221) eps = 1000. * self.mfn_line_array_target.xdata[:-1] sig_target = self.mfn_line_array_target.ydata[:-1] p.plot(eps, sig_target, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) #-------------------------------------- # phi_trail (final) #-------------------------------------- # plot the corresponding fitted phi-function # (without trial steps) # p.subplot(223) eps = 1000. * self.fitted_phi_fn.xdata[:-1] phi_fn = self.fitted_phi_fn.ydata[:-1] p.plot(eps, phi_fn, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.1f" % x, locs), fontproperties=font) # save figure with calibration process in directory # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png" simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn') if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) ctt_key = self.test_key filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf') p.savefig(filename) print 'plot_trail_steps.png saved to file %s' % (filename) filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png') p.savefig(filename, dpi=600) print 'plot_trail_steps.png saved to file %s' % (filename) p.show()
class Dashboard(object): def __init__(self, **kws): self.canvas = plt self._return_charts = kws.get('return_charts', True) self.prop = FontProperties() self.prop.set_size(10) self.prop.set_stretch('ultra-expanded') self.prop.set_style('oblique') self.prop.set_variant('small-caps') self.prop.set_weight('book') self.prop.set_family('fantasy') _mocked_meth = lambda s: print('!!! Your instance has `return_charts` ' 'set to `False`.\nDo `<your_instance>.' 'return_charts = True` and retry.') def plot(self, abs_, imas, labels, colors, save=False, save_dir='', file_name='', bar=False): """ Method which graphs `imas` against `abs_`. Testing/Example --------------- >>> x = np.arange(10)[None, :] >>> x array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) >>> ys = np.mgrid[0:3:1, 0:10:1][0, :, :] >>> ys array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]]) >>> labs = [ ... 'constant 1', ... 'constant 2', ... 'constant 3' ... ] >>> cols = [ ... 'red', 'blue', 'black' ... ] >>> pltobj = Dashboard(return_charts=True).plot( ... abs_ = x.T, ... imas = ys.T, ... labels = labs, ... colors = cols, ... ) >>> pltobj.show() # doctest: +SKIP >>> pltobj.close() >>> pltobj = Dashboard(return_charts=False).plot( ... abs_ = x.T, ... imas = ys.T, ... labels = labs, ... colors = cols, ... ) >>> pltobj.show() !!! Your instance has `return_charts` set to `False`. Do `<your_instance>.return_charts = True` and retry. """ if type(abs_).__module__ != np.__name__: lenabs_ = len(abs_) abs_ = np.array(abs_) abs_.shape = (lenabs_, 1) imas = imas.T.tolist() self.canvas.clf() for ima, label, color in zip(imas, labels, colors): if type(ima).__module__ != np.__name__: lenOrd = len(ima) ima = np.array(ima) ima.shape = (lenOrd, 1) if bar: self.canvas.bar(abs_, ima, align='center', label=label.upper(), color=color, linewidth=0) else: self.canvas.plot(abs_, ima, label=label.upper(), color=color) self.canvas.legend(prop=self.prop, loc='upper right', labelspacing=0.2, bbox_to_anchor=(1.1, 1.)) save_dir, file_name = save_dir_and_file_name(save_dir=save_dir, file_name=file_name, save=save) self.canvas.xticks(np.arange(min(abs_), max(abs_) + 1, 1.0), rotation=70) if save: self.canvas.savefig(os.path.join(save_dir, '%s.png' % file_name), bbox_inches=0, dpi=200) if self._return_charts: return self.canvas self.canvas.close() return type('msger', (object, ), { 'show': self._mocked_meth, 'close': self._mocked_meth, })
class AxisLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Save plotting parameters (required for @auto_refresh) self._parameters = parent._parameters # Set font self._label_fontproperties = FontProperties() self._ax2.yaxis.set_label_position('right') self._ax2.xaxis.set_label_position('top') system, equinox, units = wcs_util.system(self._wcs) if system['name'] == 'equatorial': if equinox == 'b1950': xtext = 'RA (B1950)' ytext = 'Dec (B1950)' else: xtext = 'RA (J2000)' ytext = 'Dec (J2000)' elif system['name'] == 'galactic': xtext = 'Galactic Longitude' ytext = 'Galactic Latitude' elif system['name'] == 'ecliptic': xtext = 'Ecliptic Longitude' ytext = 'Ecliptic Latitude' elif system['name'] == 'unknown': xunit = " (%s)" % self._wcs.cunit_x if self._wcs.cunit_x not in [ "", None ] else "" yunit = " (%s)" % self._wcs.cunit_y if self._wcs.cunit_y not in [ "", None ] else "" if len(self._wcs.cname_x) > 0: xtext = self._wcs.cname_x + xunit else: if len(self._wcs.ctype_x) == 8 and self._wcs.ctype_x[4] == '-': xtext = self._wcs.ctype_x[:4].replace('-', '') + xunit else: xtext = self._wcs.ctype_x + xunit if len(self._wcs.cname_y) > 0: ytext = self._wcs.cname_y + yunit else: if len(self._wcs.ctype_y) == 8 and self._wcs.ctype_y[4] == '-': ytext = self._wcs.ctype_y[:4].replace('-', '') + yunit else: ytext = self._wcs.ctype_y + yunit if system['inverted']: xtext, ytext = ytext, xtext self.set_xtext(xtext) self.set_ytext(ytext) self.set_xposition('bottom') self.set_yposition('left') @auto_refresh def set_xtext(self, label): """ Set the x-axis label text """ self._xlabel1 = self._ax1.set_xlabel(label) self._xlabel2 = self._ax2.set_xlabel(label) @auto_refresh def set_ytext(self, label): """ Set the y-axis label text """ self._ylabel1 = self._ax1.set_ylabel(label) self._ylabel2 = self._ax2.set_ylabel(label) @auto_refresh def set_xpad(self, pad): """ Set the x-axis label displacement, in points """ self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad) self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad) @auto_refresh def set_ypad(self, pad): """ Set the y-axis label displacement, in points """ self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad) self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the axis labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties self._xlabel1.set_fontproperties(self._label_fontproperties) self._xlabel2.set_fontproperties(self._label_fontproperties) self._ylabel1.set_fontproperties(self._label_fontproperties) self._ylabel2.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(True) else: self._xlabel2.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(False) else: self._xlabel2.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(True) else: self._ylabel2.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(False) else: self._ylabel2.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis label ('top' or 'bottom')" if position == 'bottom': self._xlabel1.set_visible(True) self._xlabel2.set_visible(False) elif position == 'top': self._xlabel1.set_visible(False) self._xlabel2.set_visible(True) else: raise ValueError("position should be one of 'top' or 'bottom'") self._xposition = position @auto_refresh def set_yposition(self, position): "Set the position of the y-axis label ('left' or 'right')" if position == 'left': self._ylabel1.set_visible(True) self._ylabel2.set_visible(False) elif position == 'right': self._ylabel1.set_visible(False) self._ylabel2.set_visible(True) else: raise ValueError("position should be one of 'left' or 'right'") self._yposition = position
class Colorbar(object): def __init__(self, parent): self._figure = parent._figure self._colorbar_axes = None self._parent = parent # Save plotting parameters (required for @auto_refresh) # self._parameters = parent._parameters self._base_settings = {} self._ticklabel_fontproperties = FontProperties() self._axislabel_fontproperties = FontProperties() def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, log_format=False, box=None, box_orientation='vertical', axis_label_text=None, axis_label_rotation=None, axis_label_pad=5): ''' Show a colorbar on the side of the image. Parameters ---------- location : str, optional Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. width : float, optional The width of the colorbar relative to the canvas size. pad : float, optional The spacing between the colorbar and the image relative to the canvas size. ticks : list, optional The position of the ticks on the colorbar. labels : bool, optional Whether to show numerical labels. log_format : bool, optional Whether to format ticks in exponential notation box : list, optional A custom box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. This overrides the location argument. box_orientation str, optional The orientation of the colorbar within the box. Can be 'horizontal' or 'vertical' axis_label_text str, optional Optional text label of the colorbar. ''' self._base_settings['location'] = location self._base_settings['width'] = width self._base_settings['pad'] = pad self._base_settings['ticks'] = ticks self._base_settings['labels'] = labels self._base_settings['log_format'] = log_format self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation self._base_settings['axis_label_text'] = axis_label_text self._base_settings['axis_label_rotation'] = axis_label_rotation self._base_settings['axis_label_pad'] = axis_label_pad if self._parent.image: if self._colorbar_axes: self._parent._figure.delaxes(self._colorbar_axes) if box is None: divider = make_axes_locatable(self._parent.ax) if location == 'right': self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes) orientation = 'vertical' elif location == 'top': self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes) orientation = 'horizontal' elif location == 'left': warnings.warn("Left colorbar not fully implemented") self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'vertical' elif location == 'bottom': warnings.warn("Bottom colorbar not fully implemented") self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'horizontal' else: raise Exception("location should be one of: right/top") self._parent._figure.add_axes(self._colorbar_axes) else: self._colorbar_axes = self._parent._figure.add_axes(box) orientation = box_orientation if log_format: format = LogFormatterMathtext() else: format = None self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, format=format, ticks=ticks) if axis_label_text: if axis_label_rotation: self._colorbar.set_label(axis_label_text, rotation=axis_label_rotation) else: self._colorbar.set_label(axis_label_text) if location == 'right': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = False tick.label2On = labels self._colorbar_axes.yaxis.set_label_position('right') self._colorbar_axes.yaxis.labelpad = axis_label_pad elif location == 'top': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = False tick.label2On = labels self._colorbar_axes.xaxis.set_label_position('top') self._colorbar_axes.xaxis.labelpad = axis_label_pad elif location == 'left': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = labels tick.label2On = False self._colorbar_axes.yaxis.set_label_position('left') self._colorbar_axes.yaxis.labelpad = axis_label_pad elif location == 'bottom': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = labels tick.label2On = False self._colorbar_axes.xaxis.set_label_position('bottom') self._colorbar_axes.xaxis.labelpad = axis_label_pad else: warnings.warn("No image is shown, therefore, no colorbar will be plotted") # @auto_refresh def update(self): if self._colorbar_axes: self.show(**self._base_settings) # @auto_refresh def hide(self): self._parent._figure.delaxes(self._colorbar_axes) self._colorbar_axes = None # @auto_refresh def _remove(self): self._parent._figure.delaxes(self._colorbar_axes) # LOCATION AND SIZE # @auto_refresh def set_location(self, location): ''' Set the location of the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. ''' self._base_settings['location'] = location self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_width(self, width): ''' Set the width of the colorbar relative to the canvas size. ''' self._base_settings['width'] = width self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_pad(self, pad): ''' Set the spacing between the colorbar and the image relative to the canvas size. ''' self._base_settings['pad'] = pad self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_ticks(self, ticks): ''' Set the position of the ticks on the colorbar. ''' self._base_settings['ticks'] = ticks self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_labels(self, labels): ''' Set whether to show numerical labels. ''' self._base_settings['labels'] = labels self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_box(self, box, box_orientation='vertical'): ''' Set the box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. The orientation of the colorbar within the box can be controlled with the box_orientation argument. ''' self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_axis_label_text(self, axis_label_text): ''' Set the colorbar label text. ''' self._base_settings['axis_label_text'] = axis_label_text self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_axis_label_rotation(self, axis_label_rotation): ''' Set the colorbar label rotation. ''' self._base_settings['axis_label_rotation'] = axis_label_rotation self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # @auto_refresh def set_axis_label_pad(self, axis_label_pad): ''' Set the colorbar label displacement, in points. ''' self._base_settings['axis_label_pad'] = axis_label_pad self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # FONT PROPERTIES # @auto_refresh def set_label_properties(self, *args, **kwargs): warnings.warn("set_label_properties is deprecated - use set_font instead", DeprecationWarning) self.set_font(*args, **kwargs) # @auto_refresh # @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): ''' Set the font of the tick labels. Parameters ---------- common: family, style, variant, stretch, weight, size, fontproperties Notes ----- Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. ''' if family: self._ticklabel_fontproperties.set_family(family) if style: self._ticklabel_fontproperties.set_style(style) if variant: self._ticklabel_fontproperties.set_variant(variant) if stretch: self._ticklabel_fontproperties.set_stretch(stretch) if weight: self._ticklabel_fontproperties.set_weight(weight) if size: self._ticklabel_fontproperties.set_size(size) if fontproperties: self._ticklabel_fontproperties = fontproperties # Update the tick label font properties for label in self._colorbar_axes.get_xticklabels(): label.set_fontproperties(self._ticklabel_fontproperties) for label in self._colorbar_axes.get_yticklabels(): label.set_fontproperties(self._ticklabel_fontproperties) # Also update the offset text font properties label = self._colorbar_axes.xaxis.get_offset_text() label.set_fontproperties(self._ticklabel_fontproperties) label = self._colorbar_axes.yaxis.get_offset_text() label.set_fontproperties(self._ticklabel_fontproperties) # @auto_refresh # @fixdocstring def set_axis_label_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): ''' Set the font of the tick labels. Parameters ---------- common: family, style, variant, stretch, weight, size, fontproperties Notes ----- Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. ''' if family: self._axislabel_fontproperties.set_family(family) if style: self._axislabel_fontproperties.set_style(style) if variant: self._axislabel_fontproperties.set_variant(variant) if stretch: self._axislabel_fontproperties.set_stretch(stretch) if weight: self._axislabel_fontproperties.set_weight(weight) if size: self._axislabel_fontproperties.set_size(size) if fontproperties: self._axislabel_fontproperties = fontproperties # Update the label font properties label = self._colorbar_axes.xaxis.get_label() label.set_fontproperties(self._axislabel_fontproperties) label = self._colorbar_axes.yaxis.get_label() label.set_fontproperties(self._axislabel_fontproperties) # FRAME PROPERTIES # @auto_refresh def set_frame_linewidth(self, linewidth): ''' Set the linewidth of the colorbar frame, in points. ''' warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_linewidth(linewidth) # @auto_refresh def set_frame_color(self, color): ''' Set the color of the colorbar frame, in points. ''' warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_edgecolor(color)
def plot_trial_steps(self): '''Plot target (sig-eps-curve of the tensile test) and trial curves and corresponding phi function together with trail steps from the iteration process. NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values within the global variables 'phi_trial_list_n' and 'sig_trial_list_n' n - index of the time steps to be considered i - index of the iteration steps performed in order to fit the target curve ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() # font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman # font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif # font.cursive : Zapf Chancery # font.monospace : Courier, Computer Modern Typewriter font.set_name('Script MT') # name = ['Times New Roman', 'Helvetica', 'Script MT'] #? font.set_family('serif') # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'] font.set_style('normal') # style = ['normal', 'italic', 'oblique'] font.set_size('small') # size = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11'] font.set_variant('normal') # variant= ['normal', 'small-caps'] font.set_weight('medium') # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] #------------------------------------------------------------------- p.figure(facecolor='white', dpi=600, figsize=(8, 6)) # white background # time list corresponding to the specified numbers of steps and step size # step_list = [n * self.step_size for n in range(self.n_steps + 1)] # get list of lists containing the trial values of 'sig_app' and 'phi_trail' # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled # within the iteration process when the method 'get_lack_of_fit" is called # phi_trial_list_n = [[1.]] + self.phi_trial_list_n sig_trial_list_n = [[0.]] + self.sig_trial_list_n xrange = 10. # plotting range for strain [mm/m] yrange = 15. # plotting range for stress [MPa] for n in range(self.n_steps): for i in range(len(phi_trial_list_n[n + 1])): x = np.array([step_list[n], step_list[n + 1]]) eps = 1000. * x # plot strains in permil on the x-axis #-------------------------------------- # sig-eps trial #-------------------------------------- # plot the numerically calculated sig-eps-curve (tensile test) # (with trial steps) # sig_trail = np.array( [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]]) p.subplot(222) p.plot(eps, sig_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange], fontproperties=font) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.0f" % x for x in locs], fontproperties=font) #-------------------------------------- # phi_trail #-------------------------------------- # plot the fitted phi-function # (with trial steps) # p.subplot(224) phi_trail = np.array( [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]]) p.plot(eps, phi_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.1f" % x for x in locs], fontproperties=font) #-------------------------------------- # sig-eps target #-------------------------------------- # plot the sig-eps-target curve (tensile test) # p.subplot(221) eps = 1000. * self.mfn_line_array_target.xdata[:-1] sig_target = self.mfn_line_array_target.ydata[:-1] p.plot(eps, sig_target, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.0f" % x for x in locs], fontproperties=font) #-------------------------------------- # phi_trail (final) #-------------------------------------- # plot the corresponding fitted phi-function # (without trial steps) # p.subplot(223) eps = 1000. * self.fitted_phi_fn.xdata[:-1] phi_fn = self.fitted_phi_fn.ydata[:-1] p.plot(eps, phi_fn, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.1f" % x for x in locs], fontproperties=font) # save figure with calibration process in directory # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png" simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn') if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) ctt_key = self.test_key filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf') p.savefig(filename) print('plot_trail_steps.png saved to file %s' % (filename)) filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png') p.savefig(filename, dpi=600) print('plot_trail_steps.png saved to file %s' % (filename)) p.show()
class Colorbar(object): def __init__(self, parent): self._figure = parent._figure self._colorbar_axes = None self._parent = parent self._base_settings = {} self._ticklabel_fontproperties = FontProperties() self._axislabel_fontproperties = FontProperties() @auto_refresh def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, log_format=False, box=None, box_orientation='vertical', axis_label_text=None, axis_label_rotation=None, axis_label_pad=5): """ Show a colorbar on the side of the image. Parameters ---------- location : str, optional Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. width : float, optional The width of the colorbar relative to the canvas size. pad : float, optional The spacing between the colorbar and the image relative to the canvas size. ticks : list, optional The position of the ticks on the colorbar. labels : bool, optional Whether to show numerical labels. log_format : bool, optional Whether to format ticks in exponential notation box : list, optional A custom box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. This overrides the location argument. box_orientation str, optional The orientation of the colorbar within the box. Can be 'horizontal' or 'vertical' axis_label_text str, optional Optional text label of the colorbar. """ self._base_settings['location'] = location self._base_settings['width'] = width self._base_settings['pad'] = pad self._base_settings['ticks'] = ticks self._base_settings['labels'] = labels self._base_settings['log_format'] = log_format self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation self._base_settings['axis_label_text'] = axis_label_text self._base_settings['axis_label_rotation'] = axis_label_rotation self._base_settings['axis_label_pad'] = axis_label_pad if self._parent.image: if self._colorbar_axes: self._figure.delaxes(self._colorbar_axes) if box is None: divider = make_axes_locatable(self._parent.ax) if location == 'right': self._colorbar_axes = divider.new_horizontal( size=width, pad=pad, axes_class=maxes.Axes) orientation = 'vertical' elif location == 'top': self._colorbar_axes = divider.new_vertical( size=width, pad=pad, axes_class=maxes.Axes) orientation = 'horizontal' elif location == 'left': warnings.warn("Left colorbar not fully implemented") self._colorbar_axes = divider.new_horizontal( size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'vertical' elif location == 'bottom': warnings.warn("Bottom colorbar not fully implemented") self._colorbar_axes = divider.new_vertical( size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'horizontal' else: raise Exception("location should be one of: right/top") self._figure.add_axes(self._colorbar_axes) else: self._colorbar_axes = self._figure.add_axes(box) orientation = box_orientation if log_format: format = LogFormatterMathtext() else: format = None self._colorbar = self._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, format=format, ticks=ticks) if axis_label_text: if axis_label_rotation: self._colorbar.set_label(axis_label_text, rotation=axis_label_rotation) else: self._colorbar.set_label(axis_label_text) if location == 'right': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1line.set_visible(True) tick.tick2line.set_visible(True) tick.label1.set_visible(False) tick.label2.set_visible(labels) self._colorbar_axes.yaxis.set_label_position('right') self._colorbar_axes.yaxis.labelpad = axis_label_pad elif location == 'top': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1line.set_visible(True) tick.tick2line.set_visible(True) tick.label1.set_visible(False) tick.label2.set_visible(labels) self._colorbar_axes.xaxis.set_label_position('top') self._colorbar_axes.xaxis.labelpad = axis_label_pad elif location == 'left': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1line.set_visible(True) tick.tick2line.set_visible(True) tick.label1.set_visible(labels) tick.label2.set_visible(False) self._colorbar_axes.yaxis.set_label_position('left') self._colorbar_axes.yaxis.labelpad = axis_label_pad elif location == 'bottom': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1line.set_visible(True) tick.tick2line.set_visible(True) tick.label1.set_visible(labels) tick.label2.set_visible(False) self._colorbar_axes.xaxis.set_label_position('bottom') self._colorbar_axes.xaxis.labelpad = axis_label_pad else: warnings.warn( "No image is shown, therefore, no colorbar will be plotted") @auto_refresh def update(self): if self._colorbar_axes: self.show(**self._base_settings) @auto_refresh def hide(self): self._figure.delaxes(self._colorbar_axes) self._colorbar_axes = None @auto_refresh def _remove(self): self._figure.delaxes(self._colorbar_axes) # LOCATION AND SIZE @auto_refresh def set_location(self, location): """ Set the location of the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. """ self._base_settings['location'] = location self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_width(self, width): """ Set the width of the colorbar relative to the canvas size. """ self._base_settings['width'] = width self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_pad(self, pad): """ Set the spacing between the colorbar and the image relative to the canvas size. """ self._base_settings['pad'] = pad self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_ticks(self, ticks): """ Set the position of the ticks on the colorbar. """ self._base_settings['ticks'] = ticks self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_labels(self, labels): """ Set whether to show numerical labels. """ self._base_settings['labels'] = labels self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_box(self, box, box_orientation='vertical'): """ Set the box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. The orientation of the colorbar within the box can be controlled with the box_orientation argument. """ self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_axis_label_text(self, axis_label_text): """ Set the colorbar label text. """ self._base_settings['axis_label_text'] = axis_label_text self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_axis_label_rotation(self, axis_label_rotation): """ Set the colorbar label rotation. """ self._base_settings['axis_label_rotation'] = axis_label_rotation self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) @auto_refresh def set_axis_label_pad(self, axis_label_pad): """ Set the colorbar label displacement, in points. """ self._base_settings['axis_label_pad'] = axis_label_pad self.show(**self._base_settings) self.set_font(fontproperties=self._ticklabel_fontproperties) self.set_axis_label_font(fontproperties=self._axislabel_fontproperties) # FONT PROPERTIES @auto_refresh def set_label_properties(self, *args, **kwargs): warnings.warn( "set_label_properties is deprecated - use set_font instead", DeprecationWarning) self.set_font(*args, **kwargs) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the tick labels. Parameters ---------- common: family, style, variant, stretch, weight, size, fontproperties Notes ----- Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._ticklabel_fontproperties.set_family(family) if style: self._ticklabel_fontproperties.set_style(style) if variant: self._ticklabel_fontproperties.set_variant(variant) if stretch: self._ticklabel_fontproperties.set_stretch(stretch) if weight: self._ticklabel_fontproperties.set_weight(weight) if size: self._ticklabel_fontproperties.set_size(size) if fontproperties: self._ticklabel_fontproperties = fontproperties # Update the tick label font properties for label in self._colorbar_axes.get_xticklabels(): label.set_fontproperties(self._ticklabel_fontproperties) for label in self._colorbar_axes.get_yticklabels(): label.set_fontproperties(self._ticklabel_fontproperties) # Also update the offset text font properties label = self._colorbar_axes.xaxis.get_offset_text() label.set_fontproperties(self._ticklabel_fontproperties) label = self._colorbar_axes.yaxis.get_offset_text() label.set_fontproperties(self._ticklabel_fontproperties) @auto_refresh @fixdocstring def set_axis_label_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the tick labels. Parameters ---------- common: family, style, variant, stretch, weight, size, fontproperties Notes ----- Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._axislabel_fontproperties.set_family(family) if style: self._axislabel_fontproperties.set_style(style) if variant: self._axislabel_fontproperties.set_variant(variant) if stretch: self._axislabel_fontproperties.set_stretch(stretch) if weight: self._axislabel_fontproperties.set_weight(weight) if size: self._axislabel_fontproperties.set_size(size) if fontproperties: self._axislabel_fontproperties = fontproperties # Update the label font properties label = self._colorbar_axes.xaxis.get_label() label.set_fontproperties(self._axislabel_fontproperties) label = self._colorbar_axes.yaxis.get_label() label.set_fontproperties(self._axislabel_fontproperties) # FRAME PROPERTIES @auto_refresh def set_frame_linewidth(self, linewidth): """ Set the linewidth of the colorbar frame, in points. """ warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_linewidth(linewidth) @auto_refresh def set_frame_color(self, color): """ Set the color of the colorbar frame, in points. """ warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_edgecolor(color)
class AxisLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Set font self._label_fontproperties = FontProperties() self._ax2.yaxis.set_label_position('right') self._ax2.xaxis.set_label_position('top') system, equinox, units = wcs_util.system(self._wcs) if system == 'equatorial': if equinox == 'b1950': self.set_xtext('RA (B1950)') self.set_ytext('Dec (B1950)') else: self.set_xtext('RA (J2000)') self.set_ytext('Dec (J2000)') elif system == 'galactic': self.set_xtext('Galactic Longitude') self.set_ytext('Galactic Latitude') else: self.set_xtext('Ecliptic Longitude') self.set_ytext('Ecliptic Latitude') self.set_xposition('bottom') self.set_yposition('left') @auto_refresh def set_xtext(self, label): """ Set the x-axis label text """ self._xlabel1 = self._ax1.set_xlabel(label) self._xlabel2 = self._ax2.set_xlabel(label) @auto_refresh def set_ytext(self, label): """ Set the y-axis label text """ self._ylabel1 = self._ax1.set_ylabel(label) self._ylabel2 = self._ax2.set_ylabel(label) @auto_refresh def set_xpad(self, pad): """ Set the x-axis label displacement, in points """ self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad) self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad) @auto_refresh def set_ypad(self, pad): """ Set the y-axis label displacement, in points """ self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad) self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the axis labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties self._xlabel1.set_fontproperties(self._label_fontproperties) self._xlabel2.set_fontproperties(self._label_fontproperties) self._ylabel1.set_fontproperties(self._label_fontproperties) self._ylabel2.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(True) else: self._xlabel2.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(False) else: self._xlabel2.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(True) else: self._ylabel2.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(False) else: self._ylabel2.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis label ('top' or 'bottom')" if position == 'bottom': self._xlabel1.set_visible(True) self._xlabel2.set_visible(False) elif position == 'top': self._xlabel1.set_visible(False) self._xlabel2.set_visible(True) else: raise Exception("position should be one of 'top' or 'bottom'") self._xposition = position @auto_refresh def set_yposition(self, position): "Set the position of the y-axis label ('left' or 'right')" if position == 'left': self._ylabel1.set_visible(True) self._ylabel2.set_visible(False) elif position == 'right': self._ylabel1.set_visible(False) self._ylabel2.set_visible(True) else: raise Exception("position should be one of 'left' or 'right'") self._yposition = position
class TickLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Save plotting parameters (required for @auto_refresh) self._parameters = parent._parameters # Set font self._label_fontproperties = FontProperties() self.set_style('plain') system, equinox, units = wcs_util.system(self._wcs) # Set default label format if self._wcs.xaxis_coord_type in ['longitude', 'latitude']: if system['name'] == 'equatorial': if self._wcs.xaxis_coord_type == 'longitude': self.set_xformat("hh:mm:ss.ss") else: self.set_xformat("dd:mm:ss.s") else: self.set_xformat("ddd.dddd") else: self.set_xformat('%g') if self._wcs.yaxis_coord_type in ['longitude', 'latitude']: if system['name'] == 'equatorial': if self._wcs.yaxis_coord_type == 'longitude': self.set_yformat("hh:mm:ss.ss") else: self.set_yformat("dd:mm:ss.s") else: self.set_yformat("ddd.dddd") else: self.set_yformat('%g') # Set major tick formatters fx1 = WCSFormatter(wcs=self._wcs, coord='x') fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.xaxis.set_major_formatter(fx1) self._ax1.yaxis.set_major_formatter(fy1) fx2 = mpl.NullFormatter() fy2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) self._ax2.yaxis.set_major_formatter(fy2) # Cursor display self._ax1._cursor_world = True self._figure.canvas.mpl_connect('key_press_event', self._set_cursor_prefs) @auto_refresh def set_xformat(self, format): ''' Set the format of the x-axis tick labels. If the x-axis type is ``longitude`` or ``latitude``, then the options are: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If the x-axis type is ``scalar``, then the format should be a valid python string format beginning with a ``%``. If one of these arguments is not specified, the format for that axis is left unchanged. ''' if self._wcs.xaxis_coord_type in ['longitude', 'latitude']: if format.startswith('%'): raise Exception( "Cannot specify Python format for longitude or latitude") try: if not self._ax1.xaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency( format, self._ax1.xaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return else: if not format.startswith('%'): raise Exception( "For scalar tick labels, format should be a Python format beginning with %" ) self._ax1.xaxis.apl_label_form = format self._ax2.xaxis.apl_label_form = format @auto_refresh def set_yformat(self, format): ''' Set the format of the y-axis tick labels. If the y-axis type is ``longitude`` or ``latitude``, then the options are: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If the y-axis type is ``scalar``, then the format should be a valid python string format beginning with a ``%``. If one of these arguments is not specified, the format for that axis is left unchanged. ''' if self._wcs.yaxis_coord_type in ['longitude', 'latitude']: if format.startswith('%'): raise Exception( "Cannot specify Python format for longitude or latitude") try: if not self._ax1.yaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency( format, self._ax1.yaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return else: if not format.startswith('%'): raise Exception( "For scalar tick labels, format should be a Python format beginning with %" ) self._ax1.yaxis.apl_label_form = format self._ax2.yaxis.apl_label_form = format @auto_refresh def set_style(self, style): """ Set the format of the x-axis tick labels. This can be 'colons' or 'plain': * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1 * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1" """ if style == 'latex': warnings.warn( "latex has now been merged with plain - whether or not to use LaTeX is controlled through set_system_latex" ) style = 'plain' if not style in ['colons', 'plain']: raise Exception("Label style should be one of colons/plain") self._ax1.xaxis.apl_labels_style = style self._ax1.yaxis.apl_labels_style = style self._ax2.xaxis.apl_labels_style = style self._ax2.yaxis.apl_labels_style = style @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the tick labels. Parameters ---------- common: family, style, variant, stretch, weight, size, fontproperties Notes ----- Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties for tick in self._ax1.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax1.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis tick labels. """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis tick labels. """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis tick labels. """ for tick in self._ax1.get_xticklabels(): tick.set_visible(True) for tick in self._ax2.get_xticklabels(): tick.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis tick labels. """ for tick in self._ax1.get_xticklabels(): tick.set_visible(False) for tick in self._ax2.get_xticklabels(): tick.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis tick labels. """ for tick in self._ax1.get_yticklabels(): tick.set_visible(True) for tick in self._ax2.get_yticklabels(): tick.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis tick labels. """ for tick in self._ax1.get_yticklabels(): tick.set_visible(False) for tick in self._ax2.get_yticklabels(): tick.set_visible(False) @auto_refresh def set_xposition(self, position): """ Set the position of the x-axis tick labels ('top' or 'bottom') """ if position == 'bottom': fx1 = WCSFormatter(wcs=self._wcs, coord='x') self._ax1.xaxis.set_major_formatter(fx1) fx2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) elif position == 'top': fx1 = mpl.NullFormatter() self._ax1.xaxis.set_major_formatter(fx1) fx2 = WCSFormatter(wcs=self._wcs, coord='x') self._ax2.xaxis.set_major_formatter(fx2) else: raise ValueError("position should be one of 'top' or 'bottom'") @auto_refresh def set_yposition(self, position): """ Set the position of the y-axis tick labels ('left' or 'right') """ if position == 'left': fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.yaxis.set_major_formatter(fy1) fy2 = mpl.NullFormatter() self._ax2.yaxis.set_major_formatter(fy2) elif position == 'right': fy1 = mpl.NullFormatter() self._ax1.yaxis.set_major_formatter(fy1) fy2 = WCSFormatter(wcs=self._wcs, coord='y') self._ax2.yaxis.set_major_formatter(fy2) else: raise ValueError("position should be one of 'left' or 'right'") def _set_cursor_prefs(self, event, **kwargs): if event.key == 'c': self._ax1._cursor_world = not self._ax1._cursor_world def _cursor_position(self, x, y): xaxis = self._ax1.xaxis yaxis = self._ax1.yaxis if self._ax1._cursor_world: xw, yw = wcs_util.pix2world(self._wcs, x, y) if self._wcs.xaxis_coord_type in ['longitude', 'latitude']: xw = au.Angle( degrees=xw, latitude=self._wcs.xaxis_coord_type == 'latitude') hours = 'h' in xaxis.apl_label_form if hours: xw = xw.tohours() if xaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif xaxis.apl_labels_style == 'colons': sep = (':', ':', '') xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep) xlabel = "".join(xlabel) else: xlabel = xaxis.apl_label_form % xw if self._wcs.yaxis_coord_type in ['longitude', 'latitude']: yw = au.Angle( degrees=yw, latitude=self._wcs.yaxis_coord_type == 'latitude') hours = 'h' in yaxis.apl_label_form if hours: yw = yw.tohours() if yaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif yaxis.apl_labels_style == 'colons': sep = (':', ':', '') ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep) ylabel = "".join(ylabel) else: ylabel = yaxis.apl_label_form % yw return "%s %s (world)" % (xlabel, ylabel) else: return "%g %g (pixel)" % (x, y)
class TickLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Set font self._label_fontproperties = FontProperties() self.set_style('plain') system, equinox, units = wcs_util.system(self._wcs) # Set default label format if system == 'equatorial': self.set_xformat("hh:mm:ss.ss") self.set_yformat("dd:mm:ss.s") else: self.set_xformat("ddd.dddd") self.set_yformat("dd.dddd") # Set major tick formatters fx1 = WCSFormatter(wcs=self._wcs, coord='x') fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.xaxis.set_major_formatter(fx1) self._ax1.yaxis.set_major_formatter(fy1) fx2 = mpl.NullFormatter() fy2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) self._ax2.yaxis.set_major_formatter(fy2) @auto_refresh def set_xformat(self, format): ''' Set the format of the x-axis tick labels: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If one of these arguments is not specified, the format for that axis is left unchanged. ''' try: if not self._ax1.xaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency( format, self._ax1.xaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return self._ax1.xaxis.apl_label_form = format self._ax2.xaxis.apl_label_form = format @auto_refresh def set_yformat(self, format): ''' Set the format of the y-axis tick labels: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If one of these arguments is not specified, the format for that axis is left unchanged. ''' try: if not self._ax1.yaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency( format, self._ax1.yaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn( "WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed." ) return self._ax1.yaxis.apl_label_form = format self._ax2.yaxis.apl_label_form = format @auto_refresh def set_style(self, style): """ Set the format of the x-axis tick labels. This can be 'colons' or 'plain': * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1 * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1" """ if style is 'latex': warnings.warn( "latex has now been merged with plain - whether or not to use LaTeX is controled through set_system_latex" ) style = 'plain' if not style in ['colons', 'plain']: raise Exception("Label style should be one of colons/plain") self._ax1.xaxis.apl_labels_style = style self._ax1.yaxis.apl_labels_style = style self._ax2.xaxis.apl_labels_style = style self._ax2.yaxis.apl_labels_style = style @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the tick labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties for tick in self._ax1.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax1.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis tick labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis tick labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(True) for tick in self._ax2.get_xticklabels(): tick.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(False) for tick in self._ax2.get_xticklabels(): tick.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(True) for tick in self._ax2.get_yticklabels(): tick.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(False) for tick in self._ax2.get_yticklabels(): tick.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis tick labels ('top' or 'bottom')" if position == 'bottom': fx1 = WCSFormatter(wcs=self._wcs, coord='x') self._ax1.xaxis.set_major_formatter(fx1) fx2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) elif position == 'top': fx1 = mpl.NullFormatter() self._ax1.xaxis.set_major_formatter(fx1) fx2 = WCSFormatter(wcs=self._wcs, coord='x') self._ax2.xaxis.set_major_formatter(fx2) else: raise Exception("position should be one of 'top' or 'bottom'") @auto_refresh def set_yposition(self, position): "Set the position of the y-axis tick labels ('left' or 'right')" if position == 'left': fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.yaxis.set_major_formatter(fy1) fy2 = mpl.NullFormatter() self._ax2.yaxis.set_major_formatter(fy2) elif position == 'right': fy1 = mpl.NullFormatter() self._ax1.yaxis.set_major_formatter(fy1) fy2 = WCSFormatter(wcs=self._wcs, coord='y') self._ax2.yaxis.set_major_formatter(fy2) else: raise Exception("position should be one of 'left' or 'right'") def _cursor_position(self, x, y): xaxis = self._ax1.xaxis yaxis = self._ax1.yaxis xw, yw = wcs_util.pix2world(self._wcs, x, y) xw = au.Angle(degrees=xw, latitude=False) yw = au.Angle(degrees=yw, latitude=True) hours = 'h' in xaxis.apl_label_form if hours: xw = xw.tohours() if xaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif xaxis.apl_labels_style == 'colons': sep = (':', ':', '') xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep) if yaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif yaxis.apl_labels_style == 'colons': sep = (':', ':', '') ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep) return string.join(xlabel, "") + " " + string.join(ylabel, "")
SimDB from matresdev.db.simdb.simdb_class import \ SimDBClass, SimDBClassExt simdb = SimDB() from pickle import dump, load from matplotlib.font_manager import FontProperties font = FontProperties() font.set_name('Script MT') font.set_family('serif') font.set_style('normal') font.set_size('large') font.set_variant('normal') font.set_weight('medium') def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''): '''format 2d-plot black and with with times legends ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() font.set_name('Script MT') font.set_family('serif') font.set_style('normal') # font.set_size('small')
xlabel='Dehnung $\epsilon$ [1E-3]', ylabel='Textilspannung $\sigma_\mathrm{tex}$ [MPa]', xlim=xlim, ylim=ylim) axes = p.gca() axes.xaxis.grid(True, which='major') axes.yaxis.grid(True, which='major') # plot legend # if legend_flag: font = FontProperties() font.set_family('serif') font.set_style('normal') font.set_size(14) font.set_variant('normal') # font.set_weight('ultralight') # leg = p.legend( prop=font, loc=legend_loc) # (loc=4: lower right) (7: center right) frame = leg.get_frame() frame.set_facecolor('white') frame.set_edgecolor('white') # set the linewidth of each legend object for legobj in leg.legendHandles: legobj.set_linewidth(1.50) # -------------------------------- # save figure # --------------------------------
class AxisLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Save plotting parameters (required for @auto_refresh) self._parameters = parent._parameters # Set font self._label_fontproperties = FontProperties() self._ax2.yaxis.set_label_position('right') self._ax2.xaxis.set_label_position('top') system, equinox, units = wcs_util.system(self._wcs) if system['name'] == 'equatorial': if equinox == 'b1950': xtext = 'RA (B1950)' ytext = 'Dec (B1950)' else: xtext = 'RA (J2000)' ytext = 'Dec (J2000)' elif system['name'] == 'galactic': xtext = 'Galactic Longitude' ytext = 'Galactic Latitude' elif system['name'] == 'ecliptic': xtext = 'Ecliptic Longitude' ytext = 'Ecliptic Latitude' elif system['name'] == 'unknown': xunit = " (%s)" % self._wcs.cunit_x if self._wcs.cunit_x not in ["", None] else "" yunit = " (%s)" % self._wcs.cunit_y if self._wcs.cunit_y not in ["", None] else "" if len(self._wcs.cname_x) > 0: xtext = self._wcs.cname_x + xunit else: if len(self._wcs.ctype_x) == 8 and self._wcs.ctype_x[4] == '-': xtext = self._wcs.ctype_x[:4].replace('-', '') + xunit else: xtext = self._wcs.ctype_x + xunit if len(self._wcs.cname_y) > 0: ytext = self._wcs.cname_y + yunit else: if len(self._wcs.ctype_y) == 8 and self._wcs.ctype_y[4] == '-': ytext = self._wcs.ctype_y[:4].replace('-', '') + yunit else: ytext = self._wcs.ctype_y + yunit if system['inverted']: xtext, ytext = ytext, xtext self.set_xtext(xtext) self.set_ytext(ytext) self.set_xposition('bottom') self.set_yposition('left') @auto_refresh def set_xtext(self, label): """ Set the x-axis label text """ self._xlabel1 = self._ax1.set_xlabel(label) self._xlabel2 = self._ax2.set_xlabel(label) @auto_refresh def set_ytext(self, label): """ Set the y-axis label text """ self._ylabel1 = self._ax1.set_ylabel(label) self._ylabel2 = self._ax2.set_ylabel(label) @auto_refresh def set_xpad(self, pad): """ Set the x-axis label displacement, in points """ self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad) self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad) @auto_refresh def set_ypad(self, pad): """ Set the y-axis label displacement, in points """ self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad) self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the axis labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties self._xlabel1.set_fontproperties(self._label_fontproperties) self._xlabel2.set_fontproperties(self._label_fontproperties) self._ylabel1.set_fontproperties(self._label_fontproperties) self._ylabel2.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(True) else: self._xlabel2.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(False) else: self._xlabel2.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(True) else: self._ylabel2.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(False) else: self._ylabel2.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis label ('top' or 'bottom')" if position == 'bottom': self._xlabel1.set_visible(True) self._xlabel2.set_visible(False) elif position == 'top': self._xlabel1.set_visible(False) self._xlabel2.set_visible(True) else: raise ValueError("position should be one of 'top' or 'bottom'") self._xposition = position @auto_refresh def set_yposition(self, position): "Set the position of the y-axis label ('left' or 'right')" if position == 'left': self._ylabel1.set_visible(True) self._ylabel2.set_visible(False) elif position == 'right': self._ylabel1.set_visible(False) self._ylabel2.set_visible(True) else: raise ValueError("position should be one of 'left' or 'right'") self._yposition = position
class TickLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Set font self._label_fontproperties = FontProperties() self.set_style('plain') system, equinox, units = wcs_util.system(self._wcs) # Set default label format if system == 'equatorial': self.set_xformat("hh:mm:ss.ss") self.set_yformat("dd:mm:ss.s") else: self.set_xformat("ddd.dddd") self.set_yformat("dd.dddd") # Set major tick formatters fx1 = WCSFormatter(wcs=self._wcs, coord='x') fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.xaxis.set_major_formatter(fx1) self._ax1.yaxis.set_major_formatter(fy1) fx2 = mpl.NullFormatter() fy2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) self._ax2.yaxis.set_major_formatter(fy2) @auto_refresh def set_xformat(self, format): ''' Set the format of the x-axis tick labels: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If one of these arguments is not specified, the format for that axis is left unchanged. ''' try: if not self._ax1.xaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency(format, self._ax1.xaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn("WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed.") return self._ax1.xaxis.apl_label_form = format self._ax2.xaxis.apl_label_form = format @auto_refresh def set_yformat(self, format): ''' Set the format of the y-axis tick labels: * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied * ``hh`` or ``dd`` - hours (or degrees) * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes) * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds) * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied. If one of these arguments is not specified, the format for that axis is left unchanged. ''' try: if not self._ax1.yaxis.apl_auto_tick_spacing: au._check_format_spacing_consistency(format, self._ax1.yaxis.apl_tick_spacing) except au.InconsistentSpacing: warnings.warn("WARNING: Requested label format is not accurate enough to display ticks. The label format will not be changed.") return self._ax1.yaxis.apl_label_form = format self._ax2.yaxis.apl_label_form = format @auto_refresh def set_style(self, style): """ Set the format of the x-axis tick labels. This can be 'colons' or 'plain': * 'colons' uses colons as separators, for example 31:41:59.26 +27:18:28.1 * 'plain' uses letters and symbols as separators, for example 31h41m59.26s +27º18'28.1" """ if style is 'latex': warnings.warn("latex has now been merged with plain - whether or not to use LaTeX is controled through set_system_latex") style = 'plain' if not style in ['colons', 'plain']: raise Exception("Label style should be one of colons/plain") self._ax1.xaxis.apl_labels_style = style self._ax1.yaxis.apl_labels_style = style self._ax2.xaxis.apl_labels_style = style self._ax2.yaxis.apl_labels_style = style @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the tick labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties for tick in self._ax1.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax1.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_xticklabels(): tick.set_fontproperties(self._label_fontproperties) for tick in self._ax2.get_yticklabels(): tick.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis tick labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis tick labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(True) for tick in self._ax2.get_xticklabels(): tick.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis tick labels """ for tick in self._ax1.get_xticklabels(): tick.set_visible(False) for tick in self._ax2.get_xticklabels(): tick.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(True) for tick in self._ax2.get_yticklabels(): tick.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis tick labels """ for tick in self._ax1.get_yticklabels(): tick.set_visible(False) for tick in self._ax2.get_yticklabels(): tick.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis tick labels ('top' or 'bottom')" if position == 'bottom': fx1 = WCSFormatter(wcs=self._wcs, coord='x') self._ax1.xaxis.set_major_formatter(fx1) fx2 = mpl.NullFormatter() self._ax2.xaxis.set_major_formatter(fx2) elif position == 'top': fx1 = mpl.NullFormatter() self._ax1.xaxis.set_major_formatter(fx1) fx2 = WCSFormatter(wcs=self._wcs, coord='x') self._ax2.xaxis.set_major_formatter(fx2) else: raise Exception("position should be one of 'top' or 'bottom'") @auto_refresh def set_yposition(self, position): "Set the position of the y-axis tick labels ('left' or 'right')" if position == 'left': fy1 = WCSFormatter(wcs=self._wcs, coord='y') self._ax1.yaxis.set_major_formatter(fy1) fy2 = mpl.NullFormatter() self._ax2.yaxis.set_major_formatter(fy2) elif position == 'right': fy1 = mpl.NullFormatter() self._ax1.yaxis.set_major_formatter(fy1) fy2 = WCSFormatter(wcs=self._wcs, coord='y') self._ax2.yaxis.set_major_formatter(fy2) else: raise Exception("position should be one of 'left' or 'right'") def _cursor_position(self, x, y): xaxis = self._ax1.xaxis yaxis = self._ax1.yaxis xw, yw = wcs_util.pix2world(self._wcs, x, y) xw = au.Angle(degrees=xw, latitude=False) yw = au.Angle(degrees=yw, latitude=True) hours = 'h' in xaxis.apl_label_form if hours: xw = xw.tohours() if xaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif xaxis.apl_labels_style == 'colons': sep = (':', ':', '') xlabel = xw.tostringlist(format=xaxis.apl_label_form, sep=sep) if yaxis.apl_labels_style in ['plain', 'latex']: sep = ('d', 'm', 's') if hours: sep = ('h', 'm', 's') elif yaxis.apl_labels_style == 'colons': sep = (':', ':', '') ylabel = yw.tostringlist(format=yaxis.apl_label_form, sep=sep) return string.join(xlabel, "") + " " + string.join(ylabel, "")
class Colorbar(object): def __init__(self, parent): self._figure = parent._figure self._colorbar_axes = None self._parent = parent # Save plotting parameters (required for @auto_refresh) self._parameters = parent._parameters self._base_settings = {} self._label_fontproperties = FontProperties() @auto_refresh def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, box=None, box_orientation='vertical'): ''' Show a colorbar on the side of the image. Optional Keyword Arguments: *location*: [ string ] Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. *width*: [ float ] The width of the colorbar relative to the canvas size. *pad*: [ float ] The spacing between the colorbar and the image relative to the canvas size. *ticks*: [ None or list ] The position of the ticks on the colorbar. *labels*: [ True or False ] Whether to show numerical labels. *box*: [ list ] A custom box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. This overrides the location argument. *box_orientation* [ str ] The orientation of the colorbar within the box. Can be 'horizontal' or 'vertical' ''' self._base_settings['location'] = location self._base_settings['width'] = width self._base_settings['pad'] = pad self._base_settings['ticks'] = ticks self._base_settings['labels'] = labels self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation if self._parent.image: if self._colorbar_axes: self._parent._figure.delaxes(self._colorbar_axes) if box is None: divider = make_axes_locatable(self._parent._ax1) if location == 'right': self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes) orientation = 'vertical' elif location == 'top': self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes) orientation = 'horizontal' elif location == 'left': warnings.warn("Left colorbar not fully implemented") self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'vertical' elif location == 'bottom': warnings.warn("Bottom colorbar not fully implemented") self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes) locator = divider.new_locator(nx=0, ny=0) self._colorbar_axes.set_axes_locator(locator) orientation = 'horizontal' else: raise Exception("location should be one of: right/top") self._parent._figure.add_axes(self._colorbar_axes) else: self._colorbar_axes = self._parent._figure.add_axes(box) orientation = box_orientation self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, ticks=ticks) if location == 'right': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = False tick.label2On = labels elif location == 'top': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = False tick.label2On = labels elif location == 'left': for tick in self._colorbar_axes.yaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = labels tick.label2On = False elif location == 'bottom': for tick in self._colorbar_axes.xaxis.get_major_ticks(): tick.tick1On = True tick.tick2On = True tick.label1On = labels tick.label2On = False else: warnings.warn("No image is shown, therefore, no colorbar will be plotted") @auto_refresh def update(self): if self._colorbar_axes: self.show(**self._base_settings) @auto_refresh def hide(self): self._parent._figure.delaxes(self._colorbar_axes) self._colorbar_axes = None @auto_refresh def _remove(self): self._parent._figure.delaxes(self._colorbar_axes) # LOCATION AND SIZE @auto_refresh def set_location(self, location): ''' Set the location of the colorbar. Should be one of 'left', 'right', 'top', 'bottom'. ''' self._base_settings['location'] = location self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) @auto_refresh def set_width(self, width): ''' Set the width of the colorbar relative to the canvas size. ''' self._base_settings['width'] = width self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) @auto_refresh def set_pad(self, pad): ''' Set the spacing between the colorbar and the image relative to the canvas size. ''' self._base_settings['pad'] = pad self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) @auto_refresh def set_ticks(self, ticks): ''' Set the position of the ticks on the colorbar. ''' self._base_settings['ticks'] = ticks self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) @auto_refresh def set_labels(self, labels): ''' Set whether to show numerical labels. ''' self._base_settings['labels'] = labels self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) @auto_refresh def set_box(self, box, box_orientation='vertical'): ''' Set the box within which to place the colorbar. This should be in the form [xmin, ymin, dx, dy] and be in relative figure units. The orientation of the colorbar within the box can be controlled with the box_orientation argument. ''' self._base_settings['box'] = box self._base_settings['box_orientation'] = box_orientation self.show(**self._base_settings) self.set_font(fontproperties=self._label_fontproperties) # FONT PROPERTIES @auto_refresh def set_label_properties(self, *args, **kwargs): warnings.warn("set_label_properties is deprecated - use set_font instead", DeprecationWarning) self.set_font(*args, **kwargs) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): ''' Set the font of the tick labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. ''' if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties for label in self._colorbar_axes.get_xticklabels(): label.set_fontproperties(self._label_fontproperties) for label in self._colorbar_axes.get_yticklabels(): label.set_fontproperties(self._label_fontproperties) # FRAME PROPERTIES @auto_refresh def set_frame_linewidth(self, linewidth): ''' Set the linewidth of the colorbar frame, in points ''' warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_linewidth(linewidth) @auto_refresh def set_frame_color(self, color): ''' Set the color of the colorbar frame, in points ''' warnings.warn("This method is not functional at this time") for key in self._colorbar_axes.spines: self._colorbar_axes.spines[key].set_edgecolor(color)
class AxisLabels(object): def __init__(self, parent): # Store references to axes self._ax1 = parent._ax1 self._ax2 = parent._ax2 self._wcs = parent._wcs self._figure = parent._figure # Set font self._label_fontproperties = FontProperties() self._ax2.yaxis.set_label_position('right') self._ax2.xaxis.set_label_position('top') system, equinox, units = wcs_util.system(self._wcs) if system == 'equatorial': if equinox == 'b1950': self.set_xtext('RA (B1950)') self.set_ytext('Dec (B1950)') else: self.set_xtext('RA (J2000)') self.set_ytext('Dec (J2000)') elif system == 'galactic': self.set_xtext('Galactic Longitude') self.set_ytext('Galactic Latitude') else: self.set_xtext('Ecliptic Longitude') self.set_ytext('Ecliptic Latitude') self.set_xposition('bottom') self.set_yposition('left') @auto_refresh def set_xtext(self, label): """ Set the x-axis label text """ self._xlabel1 = self._ax1.set_xlabel(label) self._xlabel2 = self._ax2.set_xlabel(label) @auto_refresh def set_ytext(self, label): """ Set the y-axis label text """ self._ylabel1 = self._ax1.set_ylabel(label) self._ylabel2 = self._ax2.set_ylabel(label) @auto_refresh def set_xpad(self, pad): """ Set the x-axis label displacement, in points """ self._xlabel1 = self._ax1.set_xlabel(self._xlabel1.get_text(), labelpad=pad) self._xlabel2 = self._ax2.set_xlabel(self._xlabel2.get_text(), labelpad=pad) @auto_refresh def set_ypad(self, pad): """ Set the y-axis label displacement, in points """ self._ylabel1 = self._ax1.set_ylabel(self._ylabel1.get_text(), labelpad=pad) self._ylabel2 = self._ax2.set_ylabel(self._ylabel2.get_text(), labelpad=pad) @auto_refresh @fixdocstring def set_font(self, family=None, style=None, variant=None, stretch=None, weight=None, size=None, fontproperties=None): """ Set the font of the axis labels Optional Keyword Arguments: common: family, style, variant, stretch, weight, size, fontproperties Default values are set by matplotlib or previously set values if set_font has already been called. Global default values can be set by editing the matplotlibrc file. """ if family: self._label_fontproperties.set_family(family) if style: self._label_fontproperties.set_style(style) if variant: self._label_fontproperties.set_variant(variant) if stretch: self._label_fontproperties.set_stretch(stretch) if weight: self._label_fontproperties.set_weight(weight) if size: self._label_fontproperties.set_size(size) if fontproperties: self._label_fontproperties = fontproperties self._xlabel1.set_fontproperties(self._label_fontproperties) self._xlabel2.set_fontproperties(self._label_fontproperties) self._ylabel1.set_fontproperties(self._label_fontproperties) self._ylabel2.set_fontproperties(self._label_fontproperties) @auto_refresh def show(self): """ Show the x- and y-axis labels """ self.show_x() self.show_y() @auto_refresh def hide(self): """ Hide the x- and y-axis labels """ self.hide_x() self.hide_y() @auto_refresh def show_x(self): """ Show the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(True) else: self._xlabel2.set_visible(True) @auto_refresh def hide_x(self): """ Hide the x-axis label """ if self._xposition == 'bottom': self._xlabel1.set_visible(False) else: self._xlabel2.set_visible(False) @auto_refresh def show_y(self): """ Show the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(True) else: self._ylabel2.set_visible(True) @auto_refresh def hide_y(self): """ Hide the y-axis label """ if self._yposition == 'left': self._ylabel1.set_visible(False) else: self._ylabel2.set_visible(False) @auto_refresh def set_xposition(self, position): "Set the position of the x-axis label ('top' or 'bottom')" if position == 'bottom': self._xlabel1.set_visible(True) self._xlabel2.set_visible(False) elif position == 'top': self._xlabel1.set_visible(False) self._xlabel2.set_visible(True) else: raise Exception("position should be one of 'top' or 'bottom'") self._xposition = position @auto_refresh def set_yposition(self, position): "Set the position of the y-axis label ('left' or 'right')" if position == 'left': self._ylabel1.set_visible(True) self._ylabel2.set_visible(False) elif position == 'right': self._ylabel1.set_visible(False) self._ylabel2.set_visible(True) else: raise Exception("position should be one of 'left' or 'right'") self._yposition = position