def _get_text1(self, loc): 'Get the default Text instance' # x in axes coords, y in data coords #t = Text( t = TextWithDash( x=0, y=loc, fontproperties=FontProperties(size=rcParams['tick.labelsize']), color=rcParams['tick.color'], verticalalignment='center', horizontalalignment='right', dashdirection=0, xaxis=False, ) trans = blend_xy_sep_transform(self.axes.transAxes, self.axes.transData) # offset the text leftward with a post transformation transOffset = translation_transform( Value(-1) * self._padPixels, Value(0)) trans.set_offset((0, 0), transOffset) t.set_transform(trans) #t.set_transform( self.axes.transData ) self._set_artist_props(t) return t
def __init__(self, x=0, y=0, text='', color=None, # defaults to rc params verticalalignment='bottom', horizontalalignment='left', multialignment=None, fontproperties=None, # defaults to FontProperties() rotation=None, ): Artist.__init__(self) if not is_string_like(text): raise TypeError('text must be a string type') self.cached = {} self._x, self._y = x, y if color is None: color = rcParams['text.color'] if fontproperties is None: fontproperties=FontProperties() self._color = color self.set_text(text) self._verticalalignment = verticalalignment self._horizontalalignment = horizontalalignment self._multialignment = multialignment self._rotation = rotation self._fontproperties = fontproperties self._bbox = None self._renderer = None
def __init__(self, x=0, y=0, text='', color=None, # defaults to rc params verticalalignment='bottom', horizontalalignment='left', multialignment=None, fontproperties=None, # defaults to FontProperties() rotation=None, ): Artist.__init__(self) self.cached = {} self._x, self._y = x, y if color is None: color = rcParams['text.color'] if fontproperties is None: fontproperties=FontProperties() self._color = color self._text = text self._verticalalignment = verticalalignment self._horizontalalignment = horizontalalignment self._multialignment = multialignment self._rotation = rotation self._fontproperties = fontproperties
def _get_text1(self, loc): 'Get the default Text instance' # the y loc is 3 points below the min of y axis # get the affine as an a,b,c,d,tx,ty list # x in data coords, y in axes coords #t = Text( t = TextWithDash( x=loc, y=0, fontproperties=FontProperties(size=rcParams['tick.labelsize']), color=rcParams['tick.color'], verticalalignment='top', horizontalalignment='center', dashdirection=0, xaxis=True, ) trans = blend_xy_sep_transform(self.axes.transData, self.axes.transAxes) #offset the text downward with a post transformation transOffset = translation_transform(Value(0), Value(-1) * self._padPixels) trans.set_offset((0, 0), transOffset) t.set_transform(trans) self._set_artist_props(t) return t
def set_fontproperties(self, fp): """ Set the font properties that control the text ACCEPTS: a matplotlib.font_manager.FontProperties instance """ if is_string_like(fp): fp = FontProperties(fp) self._fontproperties = fp
def __init__( self, x=0, y=0, text='', color=None, # defaults to rc params verticalalignment='bottom', horizontalalignment='left', multialignment=None, fontproperties=None, # defaults to FontProperties() rotation=None, linespacing=None, **kwargs): """ Create a :class:`~matplotlib.text.Text` instance at *x*, *y* with string *text*. Valid kwargs are %(Text)s """ Artist.__init__(self) self.cached = maxdict(5) self._x, self._y = x, y if color is None: color = rcParams['text.color'] if fontproperties is None: fontproperties = FontProperties() elif is_string_like(fontproperties): fontproperties = FontProperties(fontproperties) self.set_text(text) self.set_color(color) self._verticalalignment = verticalalignment self._horizontalalignment = horizontalalignment self._multialignment = multialignment self._rotation = rotation self._fontproperties = fontproperties self._bbox = None self._renderer = None if linespacing is None: linespacing = 1.2 # Maybe use rcParam later. self._linespacing = linespacing self.update(kwargs)
def _get_offset_text(self): # x in display coords, y in axes coords (to be updated at draw time) offsetText = Text(x=0, y=0.5, fontproperties = FontProperties(size=rcParams['ytick.labelsize']), color = rcParams['ytick.color'], verticalalignment = 'bottom', horizontalalignment = 'left', ) offsetText.set_transform(blend_xy_sep_transform(self.axes.transAxes, identity_transform()) ) self._set_artist_props(offsetText) self.offset_text_position='left' return offsetText
def _get_label(self): # x in axes coords, y in display coords (to be updated at draw # time by _update_label_positions label = Text(x=0.5, y=0, fontproperties = FontProperties(size=rcParams['axes.labelsize']), color = rcParams['axes.labelcolor'], verticalalignment='top', horizontalalignment='center', ) label.set_transform( blend_xy_sep_transform( self.axes.transAxes, identity_transform() )) self._set_artist_props(label) return label
def _get_label(self): # x in display coords (updated by _update_label_position) # y in axes coords label = Text(x=0, y=0.5, # todo: get the label position fontproperties=FontProperties(size=rcParams['axes.labelsize']), color = rcParams['axes.labelcolor'], verticalalignment='center', horizontalalignment='right', rotation='vertical', ) label.set_transform( blend_xy_sep_transform( identity_transform(), self.axes.transAxes) ) self._set_artist_props(label) return label
def _get_text2(self, loc): 'Get the default Text 2 instance' # x in data coords, y in axes coords t = Text(x=loc, y=1, fontproperties=FontProperties(size=rcParams['tick.labelsize']), color=rcParams['tick.color'], verticalalignment='bottom', horizontalalignment='center', ) trans = blend_xy_sep_transform( self.axes.transData, self.axes.transAxes) # offset the text upward with a post transformation transOffset = translation_transform( Value(0), self._padPixels) trans.set_offset( (0,0), transOffset) t.set_transform( trans ) self._set_artist_props(t) return t
def _get_texts(self, labels, left, upper): # height in axes coords HEIGHT = self._approx_text_height() pos = upper x = left ret = [] # the returned list of text instances for l in labels: text = Text( x=x, y=pos, text=l, fontproperties=FontProperties(size='smaller'), verticalalignment='top', horizontalalignment='left', ) self._set_artist_props(text) ret.append(text) pos -= HEIGHT return ret
def clabel(self, *args, **kwargs): """ CLABEL(*args, **kwargs) Function signatures CLABEL(C) - plots contour labels, C is the output of contour or a list of contours CLABEL(C,V) - creates labels only for those contours, given in a list V CLABEL(C, **kwargs) - keyword args are explained below: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = 0: controls whether the underlying contour is removed (inline = 1) or not * fmt = '%1.3f': a format string for the label """ # todo, factor this out to a separate class and don't use hidden coll attrs if not self.ax.ishold(): self.ax.cla() fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 0) fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 1: contours = args[0] levels = [con._label for con in contours] elif len(args) == 2: contours = args[0] levels = args[1] else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize fslist = [font_size] * len(levels) if colors == None: colors = [c._colors[0] for c in contours] else: colors = colors * len(contours) if inline not in [0, 1]: raise TypeError("inline must be 0 or 1") self.cl = [] self.cl_xy = [] # we have a list of contours and each contour has a list of # segments. We want changes in the contour color to be # reflected in changes in the label color. This is a good use # for traits observers, but in the interim, until traits are # utilized, we'll create a dict mapping i,j to text instances. # i is the contour level index, j is the sement index self.labeld = {} if inline == 1: self.inline_labels(levels, contours, colors, fslist, fmt) else: self.labels(levels, contours, colors, fslist, fmt) for label in self.cl: self.ax.add_artist(label) ret = silent_list('Text', self.cl) ret.mappable = getattr(contours, 'mappable', None) # support colormapping for label if ret.mappable is not None: ret.mappable.labeld = self.labeld return ret
def __init__(self, parent, handles, labels, loc, isaxes=True, numpoints = 4, # the number of points in the legend line prop = FontProperties(size='smaller'), pad = 0.2, # the fractional whitespace inside the legend border markerscale = 0.6, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = 0.005, # the vertical space between the legend entries handlelen = 0.05, # the length of the legend lines handletextsep = 0.02, # the space between the legend line and legend text axespad = 0.02, # the border between the axes and legend edge shadow=False, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties('smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) self.numpoints = numpoints self.prop = prop self.fontsize = prop.get_size_in_points() self.pad = pad self.markerscale = markerscale self.labelsep = labelsep self.handlelen = handlelen self.handletextsep = handletextsep self.axespad = axespad self.shadow = shadow if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT*len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, parent, handles, labels, loc = None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow = None ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code numpoints = 4 # the number of points in the legend line prop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ from axes import Axes # local import only to avoid circularity from figure import Figure # local import only to avoid circularity Artist.__init__(self) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow'] for name, value in safezip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if self.numpoints <= 0: raise ValueError("numpoints must be >= 0; it was %d"% numpoints) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if isinstance(parent,Axes): self.isaxes = True self.set_figure(parent.figure) elif isinstance(parent,Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._offsetTransform = Affine2D() self._parentTransform = BboxTransformTo(parent.bbox) Artist.set_transform(self, self._offsetTransform + self._parentTransform) if loc is None: loc = rcParams["legend.loc"] if not self.isaxes and loc in [0,'best']: loc = 'upper right' if is_string_like(loc): if not self.codes.has_key(loc): if self.isaxes: warnings.warn('Unrecognized location "%s". Falling back on "best"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 0 else: warnings.warn('Unrecognized location "%s". Falling back on "upper right"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 1 else: loc = self.codes[loc] if not self.isaxes and loc == 0: warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. ' 'Falling back on "upper right".') loc = 1 self._loc = loc self.legendPatch = Rectangle( xy=(0.0, 0.0), width=0.5, height=0.5, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) self._drawFrame = True
def __init__(self, parent, handles, labels, loc, isaxes= None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow= None, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): warnings.warn('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow, isaxes] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow', 'isaxes'] for name, value in zip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if self.isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) if len(self.texts): left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height()*len(self.texts) else: HEIGHT = 0.2 bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def clabel(self, *args, **kwargs): """ clabel(CS, **kwargs) - add labels to line contours in CS, where CS is a ContourSet object returned by contour. clabel(CS, V, **kwargs) - only label contours listed in V keyword arguments: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = True: controls whether the underlying contour is removed (inline = True) or not (False) * fmt = '%1.3f': a format string for the label """ fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 1) self.fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 0: levels = self.levels indices = range(len(self.levels)) elif len(args) == 1: levlabs = list(args[0]) indices, levels = [], [] for i, lev in enumerate(self.levels): if lev in levlabs: indices.append(i) levels.append(lev) if len(levels) < len(levlabs): msg = "Specified levels " + str(levlabs) msg += "\n don't match available levels " msg += str(self.levels) raise ValueError(msg) else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.label_levels = levels self.label_indices = indices self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") # Can't it be floating point, as indicated in line above? else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize self.fslist = [font_size] * len(levels) if colors == None: self.label_mappable = self self.label_cvalues = take(self.cvalues, self.label_indices) else: cmap = ListedColormap(colors, N=len(self.label_levels)) self.label_cvalues = range(len(self.label_levels)) self.label_mappable = ScalarMappable(cmap=cmap, norm=no_norm()) #self.cl = [] # Initialized in ContourSet.__init__ #self.cl_cvalues = [] # same self.cl_xy = [] self.labels(inline) for label in self.cl: self.ax.add_artist(label) self.label_list = silent_list('Text', self.cl) return self.label_list