def update(self, **kwargs): """ Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc. """ for k, v in six.iteritems(kwargs): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError("%s is unknown keyword" % (k,)) from matplotlib import _pylab_helpers from matplotlib.axes import SubplotBase for figmanager in six.itervalues(_pylab_helpers.Gcf.figs): for ax in figmanager.canvas.figure.axes: # copied from Figure.subplots_adjust if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if ax._sharex is not None and isinstance(ax._sharex, SubplotBase): if ax._sharex.get_subplotspec().get_gridspec() == self: ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ax._sharey is not None and isinstance(ax._sharey,SubplotBase): if ax._sharey.get_subplotspec().get_gridspec() == self: ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: ax.update_params() ax.set_position(ax.figbox)
def __call__(self, s): if self.ignorecase: s = s.lower() if s in self.valid: return self.valid[s] raise ValueError('Unrecognized %s string "%s": valid strings are %s' % (self.key, s, list(six.itervalues(self.valid))))
def validate_fonttype(s): """ confirm that this is a Postscript of PDF font type that we know how to convert to """ fonttypes = {"type3": 3, "truetype": 42} try: fonttype = validate_int(s) except ValueError: if s.lower() in six.iterkeys(fonttypes): return fonttypes[s.lower()] raise ValueError("Supported Postscript/PDF font types are %s" % list(six.iterkeys(fonttypes))) else: if fonttype not in six.itervalues(fonttypes): raise ValueError("Supported Postscript/PDF font types are %s" % list(six.itervalues(fonttypes))) return fonttype
def get_children(self): if self._axisline_on: children = list(six.itervalues(self._axislines)) + [self.gridlines] else: children = [] children.extend(super(Axes, self).get_children()) return children
def update(self, **kwargs): """ Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc. """ for k, v in six.iteritems(kwargs): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError("%s is unknown keyword" % (k, )) from matplotlib import _pylab_helpers from matplotlib.axes import SubplotBase for figmanager in six.itervalues(_pylab_helpers.Gcf.figs): for ax in figmanager.canvas.figure.axes: # copied from Figure.subplots_adjust if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if ax._sharex is not None and isinstance( ax._sharex, SubplotBase): if ax._sharex.get_subplotspec().get_gridspec() == self: ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ax._sharey is not None and isinstance( ax._sharey, SubplotBase): if ax._sharey.get_subplotspec().get_gridspec() == self: ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: ax.update_params() ax.set_position(ax.figbox)
def _offset(self, ox, oy): 'Move all the artists by ox,oy (axes coords)' for c in six.itervalues(self._cells): x, y = c.get_x(), c.get_y() c.set_x(x + ox) c.set_y(y + oy)
def get_tightbbox(self, renderer, call_axes_locator=True): bb0 = super(Axes, self).get_tightbbox(renderer, call_axes_locator) if not self._axisline_on: return bb0 bb = [bb0] for axisline in list(six.itervalues(self._axislines)): if not axisline.get_visible(): continue bb.append(axisline.get_tightbbox(renderer)) # if axisline.label.get_visible(): # bb.append(axisline.label.get_window_extent(renderer)) # if axisline.major_ticklabels.get_visible(): # bb.extend(axisline.major_ticklabels.get_window_extents(renderer)) # if axisline.minor_ticklabels.get_visible(): # bb.extend(axisline.minor_ticklabels.get_window_extents(renderer)) # if axisline.major_ticklabels.get_visible() or \ # axisline.minor_ticklabels.get_visible(): # bb.append(axisline.offsetText.get_window_extent(renderer)) #bb.extend([c.get_window_extent(renderer) for c in artists \ # if c.get_visible()]) _bbox = Bbox.union([b for b in bb if b and (b.width!=0 or b.height!=0)]) return _bbox
def _auto_set_font_size(self, renderer): if len(self._cells) == 0: return fontsize = list(six.itervalues(self._cells))[0].get_fontsize() cells = [] for key, cell in six.iteritems(self._cells): # ignore auto-sized columns if key[1] in self._autoColumns: continue size = cell.auto_set_font_size(renderer) fontsize = min(fontsize, size) cells.append(cell) # now set all fontsizes equal for cell in six.itervalues(self._cells): cell.set_fontsize(fontsize)
def get_window_extent(self, renderer): 'Return the bounding box of the table in window coords' boxes = [ cell.get_window_extent(renderer) for cell in six.itervalues(self._cells) ] return Bbox.union(boxes)
def destroy_fig(cls, fig): "*fig* is a Figure instance" num = None for manager in six.itervalues(cls.figs): if manager.canvas.figure == fig: num = manager.num break if num is not None: cls.destroy(num)
def validate_fonttype(s): """ confirm that this is a Postscript of PDF font type that we know how to convert to """ fonttypes = {'type3': 3, 'truetype': 42} try: fonttype = validate_int(s) except ValueError: if s.lower() in six.iterkeys(fonttypes): return fonttypes[s.lower()] raise ValueError('Supported Postscript/PDF font types are %s' % list(six.iterkeys(fonttypes))) else: if fonttype not in six.itervalues(fonttypes): raise ValueError('Supported Postscript/PDF font types are %s' % list(six.itervalues(fonttypes))) return fonttype
def set_fontsize(self, size): """ Set the fontsize of the cell text ACCEPTS: a float in points """ for cell in six.itervalues(self._cells): cell.set_fontsize(size) self.stale = True
def __getitem__(self, k): if isinstance(k, tuple): r = SimpleChainedObjects([dict.__getitem__(self, k1) for k1 in k]) return r elif isinstance(k, slice): if k.start == None and k.stop == None and k.step == None: r = SimpleChainedObjects(list(six.itervalues(self))) return r else: raise ValueError("Unsupported slice") else: return dict.__getitem__(self, k)
def _write_clips(self): if not len(self._clipd): return writer = self.writer writer.start('defs') for clip, oid in six.itervalues(self._clipd): writer.start('clipPath', id=oid) if len(clip) == 2: clippath, clippath_trans = clip path_data = self._convert_path(clippath, clippath_trans, simplify=False) writer.element('path', d=path_data) else: x, y, w, h = clip writer.element('rect', x=six.text_type(x), y=six.text_type(y), width=six.text_type(w), height=six.text_type(h)) writer.end('clipPath') writer.end('defs')
def _write_hatches(self): if not len(self._hatchd): return HATCH_SIZE = 72 writer = self.writer writer.start('defs') for ((path, face, stroke), oid) in six.itervalues(self._hatchd): writer.start('pattern', id=oid, patternUnits="userSpaceOnUse", x="0", y="0", width=six.text_type(HATCH_SIZE), height=six.text_type(HATCH_SIZE)) path_data = self._convert_path(path, Affine2D().scale(HATCH_SIZE).scale( 1.0, -1.0).translate(0, HATCH_SIZE), simplify=False) if face is None: fill = 'none' else: fill = rgb2hex(face) writer.element('rect', x="0", y="0", width=six.text_type(HATCH_SIZE + 1), height=six.text_type(HATCH_SIZE + 1), fill=fill) writer.element('path', d=path_data, style=generate_css({ 'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), 'stroke-width': six.text_type(rcParams['hatch.linewidth']), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' })) writer.end('pattern') writer.end('defs')
def ttfdict_to_fnames(d): """ flatten a ttfdict to all the filenames it contains """ fnames = [] for named in six.itervalues(d): for styled in six.itervalues(named): for variantd in six.itervalues(styled): for weightd in six.itervalues(variantd): for stretchd in six.itervalues(weightd): for fname in six.itervalues(stretchd): fnames.append(fname) return fnames
def recursive_pickle(top_obj): """ Recursively pickle all of the given objects subordinates, starting with the deepest first. **Very** handy for debugging pickling issues, but also very slow (as it literally pickles each object in turn). Handles circular object references gracefully. """ objs = depth_getter(top_obj) # sort by depth then by nest_info objs = sorted(six.itervalues(objs), key=lambda val: (-val[0], val[2])) for _, obj, location in objs: try: pickle.dump(obj, BytesIO(), pickle.HIGHEST_PROTOCOL) except Exception as err: print(obj) print("Failed to pickle %s. \n Type: %s. Traceback " "follows:" % (location, type(obj))) raise
def recursive_pickle(top_obj): """ Recursively pickle all of the given objects subordinates, starting with the deepest first. **Very** handy for debugging pickling issues, but also very slow (as it literally pickles each object in turn). Handles circular object references gracefully. """ objs = depth_getter(top_obj) # sort by depth then by nest_info objs = sorted(six.itervalues(objs), key=lambda val: (-val[0], val[2])) for _, obj, location in objs: try: pickle.dump(obj, BytesIO(), pickle.HIGHEST_PROTOCOL) except Exception as err: print(obj) print('Failed to pickle %s. \n Type: %s. Traceback ' 'follows:' % (location, type(obj))) raise
def _write_clips(self): if not len(self._clipd): return writer = self.writer writer.start('defs') for clip, oid in six.itervalues(self._clipd): writer.start('clipPath', id=oid) if len(clip) == 2: clippath, clippath_trans = clip path_data = self._convert_path(clippath, clippath_trans, simplify=False) writer.element('path', d=path_data) else: x, y, w, h = clip writer.element('rect', x=short_float_fmt(x), y=short_float_fmt(y), width=short_float_fmt(w), height=short_float_fmt(h)) writer.end('clipPath') writer.end('defs')
def _write_hatches(self): if not len(self._hatchd): return HATCH_SIZE = 72 writer = self.writer writer.start('defs') for ((path, face, stroke), oid) in six.itervalues(self._hatchd): writer.start( 'pattern', id=oid, patternUnits="userSpaceOnUse", x="0", y="0", width=six.text_type(HATCH_SIZE), height=six.text_type(HATCH_SIZE)) path_data = self._convert_path( path, Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), simplify=False) if face is None: fill = 'none' else: fill = rgb2hex(face) writer.element( 'rect', x="0", y="0", width=six.text_type(HATCH_SIZE+1), height=six.text_type(HATCH_SIZE+1), fill=fill) writer.element( 'path', d=path_data, style=generate_css({ 'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), 'stroke-width': '1.0', 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' }) ) writer.end('pattern') writer.end('defs')
def curvelinear_test3(fig): """ polar projection, but in a rectangular box. """ global ax1, axis import numpy as np from . import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) # Find a grid values appropriate for the coordinate (degree, # minute, second). tick_formatter1 = angle_helper.FormatterDMS() # And also uses an appropriate formatter. Note that,the # acceptable Locator and Formatter class is a bit different than # that of mpl's, and you cannot directly use mpl's Locator and # Formatter here (but may be possible in the future). grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) for axis in list(six.itervalues(ax1.axis)): axis.set_visible(False) fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() ax1.axis["lat1"] = axis = grid_helper.new_floating_axis( 0, 130, axes=ax1, axis_direction="left") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 grid_helper = ax1.get_grid_helper() ax1.axis["lat2"] = axis = grid_helper.new_floating_axis( 0, 50, axes=ax1, axis_direction="right") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lon"] = axis = grid_helper.new_floating_axis( 1, 10, axes=ax1, axis_direction="bottom") axis.label.set_text("Test 2") axis.get_helper()._extremes = 50, 130 axis.major_ticklabels.set_axis_direction("top") axis.label.set_axis_direction("top") grid_helper.grid_finder.grid_locator1.den = 5 grid_helper.grid_finder.grid_locator2._nbins = 5 # # A parasite axes with given transform # ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # # note that ax2.transData == tr + ax1.transData # # Anthing you draw in ax2 will match the ticks and grids of ax1. # ax1.parasites.append(ax2) # intp = cbook.simple_linear_interpolation # ax2.plot(intp(np.array([0, 30]), 50), # intp(np.array([10., 10.]), 50)) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def curvelinear_test3(fig): """ polar projection, but in a rectangular box. """ global ax1, axis import numpy as np from . import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi / 180.0, 1.0) + PolarAxes.PolarTransform() # polar projection, which involves cycle, and also has limits in # its coordinates, needs a special method to find the extremes # (min, max of the coordinate within the view). # 20, 20 : number of sampling points along x, y direction extreme_finder = angle_helper.ExtremeFinderCycle( 20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf) ) grid_locator1 = angle_helper.LocatorDMS(12) # Find a grid values appropriate for the coordinate (degree, # minute, second). tick_formatter1 = angle_helper.FormatterDMS() # And also uses an appropriate formatter. Note that,the # acceptable Locator and Formatter class is a bit different than # that of mpl's, and you cannot directly use mpl's Locator and # Formatter here (but may be possible in the future). grid_helper = GridHelperCurveLinear( tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1 ) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) for axis in list(six.itervalues(ax1.axis)): axis.set_visible(False) fig.add_subplot(ax1) grid_helper = ax1.get_grid_helper() ax1.axis["lat1"] = axis = grid_helper.new_floating_axis(0, 130, axes=ax1, axis_direction="left") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 grid_helper = ax1.get_grid_helper() ax1.axis["lat2"] = axis = grid_helper.new_floating_axis(0, 50, axes=ax1, axis_direction="right") axis.label.set_text("Test") axis.label.set_visible(True) axis.get_helper()._extremes = 0.001, 10 ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 10, axes=ax1, axis_direction="bottom") axis.label.set_text("Test 2") axis.get_helper()._extremes = 50, 130 axis.major_ticklabels.set_axis_direction("top") axis.label.set_axis_direction("top") grid_helper.grid_finder.grid_locator1.den = 5 grid_helper.grid_finder.grid_locator2._nbins = 5 # # A parasite axes with given transform # ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # # note that ax2.transData == tr + ax1.transData # # Anthing you draw in ax2 will match the ticks and grids of ax1. # ax1.parasites.append(ax2) # intp = cbook.simple_linear_interpolation # ax2.plot(intp(np.array([0, 30]), 50), # intp(np.array([10., 10.]), 50)) ax1.set_aspect(1.0) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True)
def get_children(self): 'Return the Artists contained by the table' return list(six.itervalues(self._cells))
def get_window_extent(self, renderer): 'Return the bounding box of the table in window coords' boxes = [cell.get_window_extent(renderer) for cell in six.itervalues(self._cells)] return Bbox.union(boxes)
def scale(self, xscale, yscale): """ Scale column widths by xscale and row heights by yscale. """ for c in six.itervalues(self._cells): c.set_width(c.get_width() * xscale) c.set_height(c.get_height() * yscale)