def extl(self, v): """ Casts input argument as a list and ensures it is at least as long as levels :param v: Some variable :return: List of values for variable v; at least as long as self.levels """ return tolist(v) * int(np.ceil(len(self.levels) / len(tolist(v))))
def _deleted_axes_protection(self, method=None): """Checks whether axes have been deleted by Qt and sets self.axes to None if they have""" try: tolist(self.axes) except RuntimeError: m = ' ({})'.format(method) if method is not None else '' print( 'Warning: Qt has deleted the axes; figure had a residual reference to a bad Qt object.{}' .format(m)) self.axes = None
def _cleanup_legend_labels(handles, labels): nlab = len(np.atleast_1d(labels)) if labels is not None and nlab == 1: labels = tolist(labels)*len(handles) elif labels is not None and nlab == len(handles): labels = tolist(labels) else: handles = [item for item in handles if hasattr(item, 'name') and item.name() is not None] labels = [item.name() for item in handles] return handles, labels
def _setup_scatter_symbol_pen(brush_edges, linewidths): """Sets up the pen for drawing symbols on scatter plot""" sympen_kw = [{'color': cc} for cc in brush_edges] if linewidths is not None: n = len(brush_edges) if (len(tolist(linewidths)) == 1) and (n > 1): # Make list of lw the same length as x for cases where only one setting value was provided linewidths = tolist(linewidths) * n for i in range(n): sympen_kw[i]['width'] = linewidths[i] return [pg.mkPen(**spkw) for spkw in sympen_kw]
def test_tolist(self): ar = np.array([1, 2, 3]) a2 = np.zeros((3, 3)) bo = True li = [1, 2, 3] no = None sc = 0 st = 'blah' tu = (1, 2) for thing in [ar, a2, bo, li, no, sc, st, tu]: assert isinstance(tolist(thing), list) assert isinstance(tolist(thing) + [1, 2, 3], list)
def _set_up_imange_extent(self, x, **kwargs): """ Handles setup of image extent, translate, and scale """ origin = kwargs.pop('origin', None) if origin in ['upper', None]: x = x[::-1] extent = kwargs.pop('extent', None) or (-0.5, x.shape[1] - 0.5, -(x.shape[0] - 0.5), -(0 - 0.5)) else: extent = kwargs.pop('extent', None) or (-0.5, x.shape[1] - 0.5, -0.5, x.shape[0] - 0.5) if len(np.shape(x)) == 3: x = np.transpose(x, (2, 0, 1)) else: x = np.array( color_map_translator( x.flatten(), cmap=self.cmap, norm=self.norm, vmin=self.vmin, vmax=self.vmax, clip=kwargs.pop('clip', False), ncol=kwargs.pop('N', 256), alpha=self.alpha, )).T.reshape([4] + tolist(x.shape)) super(AxesImage, self).__init__(np.transpose(x)) self.resetTransform() self.translate(extent[0], extent[2]) self.scale(int(round((extent[1] - extent[0]) / self.width())), int(round((extent[3] - extent[2]) / self.height())))
def handle_info(handles, comment=None): """For debugging: prints information on legend handles""" if comment is not None: printd(comment) for i, handle in enumerate(tolist(handles)): printd(' {i:02d} handle name: {name:}, class: {cls:}, isVisible: {isvis:}'.format( i=i, name=getattr(handle, 'name', None), cls=getattr(handle, '__class__', ' not found '), isvis=getattr(handle, 'isVisible', None), ))
def color_map_translator(x, **kw): """ Translates colors for a matplotlib colormap and a dataset, such as would be used for scatter, imshow, contour, etc. :param x: numeric scalar or iterable Data to be mapped. Very boring if scalar. :param cmap: string Color map nape, passed to matplotlib.cm.get_cmap() :param norm: matplotlib normalization class Defaults to new instance of mpl.colors.Normalize :param vmin: numeric Lower limit passed to new Normalize instance if norm is None; ignored if norm is provided. :param vmax: numeric Lower limit passed to new Normalize instance if norm is None; ignored if norm is provided. :param clip: bool Passed to Normalize if a new Normalize instance is created. Otherwise, not used. :param ncol: int passed to Colormap to set number of colors :param alpha: float: opacity from 0 to 1 or None :return: list List of pyqtgraph-compatible color specifications with length matching x """ printd('color_map_translator...') norm = kw.pop('norm', None) if norm is None: printd(' norm was None, normalizing...') norm = Normalize(vmin=kw.pop('vmin', None), vmax=kw.pop('vmax', None), clip=kw.pop('clip', False)) comap = matplotlib.cm.get_cmap(kw.pop('cmap', None), lut=kw.pop('ncol', 256)) colors = comap(norm(np.atleast_1d(x))) return [ color_translator(color=color, alpha=kw.get('alpha', None)) for color in tolist(colors) ]
def add_subplot(self, nrows, ncols, index, **kwargs): """Imitation of matplotlib.figure.Figure.add_subplot""" check_unimplemented_keywords(['projection', 'polar'], method='add_subplot', **kwargs) row = int(np.floor((index - 1) / ncols)) if row > (nrows - 1): raise ValueError( 'index {} would be on row {}, but the last row is {}!'.format( index, row, nrows - 1)) col = (index - 1) % ncols ax = Axes(nrows=nrows, ncols=ncols, index=index, **kwargs) self.layout.addItem(ax, row + 1, col) self._deleted_axes_protection('add_subplot') self.axes = ax if self.axes is None else tolist(self.axes) + [ax] self.fig_colspan = max([ncols, self.fig_colspan]) self.refresh_suptitle() return ax
def __call__(self, handles=None, labels=None, **kw): """ Adds a legend to the plot axes. This class should be added to axes as they are created so that calling it acts like a method of the class and adds a legend, imitating matplotlib legend calling. """ printd(' custom legend call') self.leg = self.ax.addLegend() # ax.addLegend modifies ax.legend, so we have to put it back in order to # preserve a reference to pgmpl.axes.Legend. self.ax.legend = self handles = tolist(handles if handles is not None else self.get_visible_handles()) for handle, label in zip(*self._cleanup_legend_labels(handles, labels)): if self.supported(handle): self.leg.addItem(handle, label) self.check_call_kw(**kw) return self
def _prep_scatter_colors(n, **kwargs): """ Helper function to prepare colors for scatter plot :param n: int Number of colors to prepare :param kwargs: keywords for controlling color, like c edgecolors alpha :return: tuple list of colors for primary usage (maybe for face, line, etc.) list of colors for edges """ edgecolors = kwargs.pop('edgecolors', None) c = kwargs.pop('c', None) # Translate face colors if c is None: # All same default color brush_colors = [color_translator(color='b')] * n elif is_numeric(tolist(c)[0]): brush_colors = color_map_translator(c, **kwargs) else: # Assume that c is a list/array of colors brush_colors = [color_translator(color=cc) for cc in tolist(c)] # Translate edge colors brush_edges = [color_translator(color='k')] * n if edgecolors is None \ else [color_translator(color=ec, alpha=kwargs.get('alpha', None)) for ec in tolist(edgecolors)] # Make the lists of symbol settings the same length as x for cases where only one setting value was provided brush_colors = tolist(brush_colors) * n if (len( tolist(brush_colors)) == 1) and (n > 1) else brush_colors brush_edges = tolist(brush_edges) * n if (len( tolist(brush_edges)) == 1) and (n > 1) else brush_edges return brush_colors, brush_edges