def on_combobox_lineprops_changed(self, item): "update the widgets from the active line" if not self._inited: return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if ls is None: ls = "None" self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if marker is None: marker = "None" self.cbox_markers.set_active(self.markerd[marker]) rgba = mcolors.to_rgba(line.get_color()) color = gtk.gdk.Color(*[int(val * 65535) for val in rgba[:3]]) button = self.wtree.get_widget("colorbutton_linestyle") button.set_color(color) rgba = mcolors.to_rgba(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val * 65535) for val in rgba[:3]]) button = self.wtree.get_widget("colorbutton_markerface") button.set_color(color) self._updateson = True
def volume_overlay(ax, opens, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence a sequence of opens closes : sequence a sequence of closes volumes : sequence a sequence of volumes width : int the bar width in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : `barCollection` The `barrCollection` added to the axes """ colorup = mcolors.to_rgba(colorup, alpha) colordown = mcolors.to_rgba(colordown, alpha) colord = {True: colorup, False: colordown} colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] delta = width / 2. bars = [((i - delta, 0), (i - delta, v), (i + delta, v), (i + delta, 0)) for i, v in enumerate(volumes) if v != -1] barCollection = PolyCollection(bars, facecolors=colors, edgecolors=((0, 0, 0, 1), ), antialiaseds=(0,), linewidths=(0.5,), ) ax.add_collection(barCollection) corners = (0, 0), (len(bars), max(volumes)) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow', alpha=1.0): self.fontsize = fontsize self.labelcolor = labelcolor self.bgcolor = bgcolor self.alpha = alpha self.labelcolor_rgb = colors.to_rgba(labelcolor)[:3] self.bgcolor_rgb = colors.to_rgba(bgcolor)[:3]
def test_legend_edgecolor(): get_func = 'get_edgecolor' rcparam = 'legend.edgecolor' test_values = [({rcparam: 'r'}, mcolors.to_rgba('r')), ({rcparam: 'inherit', 'axes.edgecolor': 'r'}, mcolors.to_rgba('r')), ({rcparam: 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g'))] for rc_dict, target in test_values: yield _legend_rcparam_helper, rc_dict, target, get_func
def test_conversions(): # to_rgba_array("none") returns a (0, 4) array. assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) # alpha is properly set. assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5)) # builtin round differs between py2 and py3. assert_equal(mcolors.to_hex((.7, .7, .7)), "#b2b2b2") # hex roundtrip. hex_color = "#1234abcd" assert_equal(mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True), hex_color)
def test_failed_conversions(): with pytest.raises(ValueError): mcolors.to_rgba('5') with pytest.raises(ValueError): mcolors.to_rgba('-1') with pytest.raises(ValueError): mcolors.to_rgba('nan') with pytest.raises(ValueError): mcolors.to_rgba('unknown_color') with pytest.raises(ValueError): # Gray must be a string to distinguish 3-4 grays from RGB or RGBA. mcolors.to_rgba(0.4)
def convert_colors_string_to_tuple(cols): for col in cols: if isinstance(col, str): if col in BASE_COLORS: yield to_rgba(BASE_COLORS[col]) elif col in CSS4_COLORS: yield to_rgba(CSS4_COLORS[col]) else: raise ValueError("Color specifier {} " "not recognized".format(col)) else: yield to_rgba(col)
def draw_3d(verts, ymin, ymax, line_at_zero=True, colors=True): '''Given verts as a list of plots, each plot being a list of (x, y) vertices, generate a 3-d figure where each plot is shown as a translucent polygon. If line_at_zero, a line will be drawn through the zero point of each plot, otherwise the baseline will be at the bottom of the plot regardless of where the zero line is. ''' # add_collection3d() wants a collection of closed polygons; # each polygon needs a base and won't generate it automatically. # So for each subplot, add a base at ymin. if line_at_zero: zeroline = 0 else: zeroline = ymin for p in verts: p.insert(0, (p[0][0], zeroline)) p.append((p[-1][0], zeroline)) if colors: # All the matplotlib color sampling examples I can find, # like cm.rainbow/linspace, make adjacent colors similar, # the exact opposite of what most people would want. # So cycle hue manually. hue = 0 huejump = .27 facecolors = [] edgecolors = [] for v in verts: hue = (hue + huejump) % 1 c = mcolors.hsv_to_rgb([hue, 1, 1]) # random.uniform(.8, 1), # random.uniform(.7, 1)]) edgecolors.append(c) # Make the facecolor translucent: facecolors.append(mcolors.to_rgba(c, alpha=.7)) else: facecolors = (1, 1, 1, .8) edgecolors = (0, 0, 1, 1) poly = PolyCollection(verts, facecolors=facecolors, edgecolors=edgecolors) zs = range(len(data)) # zs = range(len(data)-1, -1, -1) fig = plt.figure() ax = fig.add_subplot(1,1,1, projection='3d') plt.tight_layout(pad=2.0, w_pad=10.0, h_pad=3.0) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim3d(0, len(data[1])) ax.set_ylim3d(-1, len(data)) ax.set_zlim3d(ymin, ymax)
def make_image(self, renderer, magnification=1.0, unsampled=False): if self._A is None: raise RuntimeError('You must first set the image array') if unsampled: raise ValueError('unsampled not supported on PColorImage') fc = self.axes.patch.get_facecolor() bg = mcolors.to_rgba(fc, 0) bg = (np.array(bg)*255).astype(np.uint8) l, b, r, t = self.axes.bbox.extents width = (np.round(r) + 0.5) - (np.round(l) - 0.5) height = (np.round(t) + 0.5) - (np.round(b) - 0.5) # The extra cast-to-int is only needed for python2 width = int(np.round(width * magnification)) height = int(np.round(height * magnification)) if self._rgbacache is None: A = self.to_rgba(self._A, bytes=True) self._rgbacache = A if self._A.ndim == 2: self.is_grayscale = self.cmap.is_gray() else: A = self._rgbacache vl = self.axes.viewLim im = _image.pcolor2(self._Ax, self._Ay, A, height, width, (vl.x0, vl.x1, vl.y0, vl.y1), bg) return im, l, b, IdentityTransform()
def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs): """ Parameters ---------- offset : pair of floats The offset to apply to the path, in points. shadow_color : color The shadow color. Default is black. A value of ``None`` takes the original artist's color with a scale factor of `rho`. alpha : float The alpha transparency of the created shadow patch. Default is 0.3. rho : float A scale factor to apply to the rgbFace color if `shadow_rgbFace` is ``None``. Default is 0.3. **kwargs Extra keywords are stored and passed through to :meth:`AbstractPathEffect._update_gc`. """ super().__init__(offset) if shadow_color is None: self._shadow_color = shadow_color else: self._shadow_color = mcolors.to_rgba(shadow_color) self._alpha = alpha self._rho = rho #: The dictionary of keywords to update the graphics collection with. self._gc = kwargs
def print_jpg(self, filename_or_obj, *args, **kwargs): """ Supported kwargs: *quality*: The image quality, on a scale from 1 (worst) to 95 (best). The default is 95, if not given in the matplotlibrc file in the savefig.jpeg_quality parameter. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage. *optimize*: If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings. *progressive*: If present, indicates that this image should be stored as a progressive JPEG file. """ buf, size = self.print_to_buffer() if kwargs.pop("dryrun", False): return # The image is "pasted" onto a white background image to safely # handle any transparency image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) rgba = mcolors.to_rgba(rcParams.get('savefig.facecolor', 'white')) color = tuple([int(x * 255.0) for x in rgba[:3]]) background = Image.new('RGB', size, color) background.paste(image, image) options = restrict_dict(kwargs, ['quality', 'optimize', 'progressive']) if 'quality' not in options: options['quality'] = rcParams['savefig.jpeg_quality'] return background.save(filename_or_obj, format='jpeg', **options)
def get_color_range(n): colors = mcolors.TABLEAU_COLORS by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name) for name, color in colors.items()) sorted_names = [name for hsv, name in by_hsv] delta = int(len(sorted_names)/n) return sorted_names[::delta]
def test_conversions(): # to_rgba_array("none") returns a (0, 4) array. assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) # a list of grayscale levels, not a single color. assert_array_equal( mcolors.to_rgba_array([".2", ".5", ".8"]), np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]])) # alpha is properly set. assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5) assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5) # builtin round differs between py2 and py3. assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2" # hex roundtrip. hex_color = "#1234abcd" assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \ hex_color
def test_conversions_masked(): x1 = np.ma.array(['k', 'b'], mask=[True, False]) x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]]) x2[0] = np.ma.masked assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0) assert_array_equal(mcolors.to_rgba_array(x1), [[0, 0, 0, 0], [0, 0, 1, 1]]) assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1))
def to_qcolor(color): """Create a QColor from a matplotlib color""" qcolor = QtGui.QColor() try: rgba = mcolors.to_rgba(color) except ValueError: warnings.warn('Ignoring invalid color %r' % color) return qcolor # return invalid QColor qcolor.setRgbF(*rgba) return qcolor
def print_jpg(self, filename_or_obj, *args, dryrun=False, pil_kwargs=None, **kwargs): """ Write the figure to a JPEG file. Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to. Other Parameters ---------------- quality : int The image quality, on a scale from 1 (worst) to 100 (best). The default is :rc:`savefig.jpeg_quality`. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage. optimize : bool If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings. progressive : bool If present, indicates that this image should be stored as a progressive JPEG file. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.save` when saving the figure. These take precedence over *quality*, *optimize* and *progressive*. """ buf, size = self.print_to_buffer() if dryrun: return # The image is "pasted" onto a white background image to safely # handle any transparency image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) rgba = mcolors.to_rgba(rcParams['savefig.facecolor']) color = tuple([int(x * 255) for x in rgba[:3]]) background = Image.new('RGB', size, color) background.paste(image, image) if pil_kwargs is None: pil_kwargs = {} for k in ["quality", "optimize", "progressive"]: if k in kwargs: pil_kwargs.setdefault(k, kwargs[k]) pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"]) pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi)) return background.save( filename_or_obj, format='jpeg', **pil_kwargs)
def plot_colortable(colors, title, sort_colors=True, emptycols=0): cell_width = 212 cell_height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sort colors by hue, saturation, value and name. by_hsv = ((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name) for name, color in colors.items()) if sort_colors is True: by_hsv = sorted(by_hsv) names = [name for hsv, name in by_hsv] n = len(names) ncols = 4 - emptycols nrows = n // ncols + int(n % ncols > 0) width = cell_width * 4 + 2 * margin height = cell_height * nrows + margin + topmargin dpi = 72 fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi) fig.subplots_adjust(margin/width, margin/height, (width-margin)/width, (height-topmargin)/height) ax.set_xlim(0, cell_width * 4) ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.) ax.yaxis.set_visible(False) ax.xaxis.set_visible(False) ax.set_axis_off() ax.set_title(title, fontsize=24, loc="left", pad=10) for i, name in enumerate(names): row = i % nrows col = i // nrows y = row * cell_height swatch_start_x = cell_width * col swatch_end_x = cell_width * col + swatch_width text_pos_x = cell_width * col + swatch_width + 7 ax.text(text_pos_x, y, name, fontsize=14, horizontalalignment='left', verticalalignment='center') ax.hlines(y, swatch_start_x, swatch_end_x, color=colors[name], linewidth=18) return fig
def print_jpg(self, filename_or_obj, *args, dryrun=False, **kwargs): """ Write the figure to a JPEG file. Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to. Other Parameters ---------------- quality : int The image quality, on a scale from 1 (worst) to 100 (best). The default is :rc:`savefig.jpeg_quality`. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage. optimize : bool If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings. progressive : bool If present, indicates that this image should be stored as a progressive JPEG file. """ buf, size = self.print_to_buffer() if dryrun: return # The image is "pasted" onto a white background image to safely # handle any transparency image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) rgba = mcolors.to_rgba(rcParams['savefig.facecolor']) color = tuple([int(x * 255) for x in rgba[:3]]) background = Image.new('RGB', size, color) background.paste(image, image) options = {k: kwargs[k] for k in ['quality', 'optimize', 'progressive', 'dpi'] if k in kwargs} options.setdefault('quality', rcParams['savefig.jpeg_quality']) if 'dpi' in options: # Set the same dpi in both x and y directions options['dpi'] = (options['dpi'], options['dpi']) return background.save(filename_or_obj, format='jpeg', **options)
def get_colors(c, num): """Stretch the color argument to provide the required number num""" if type(c) == type("string"): c = mcolors.to_rgba(c) if iscolor(c): return [c] * num if len(c) == num: return c elif iscolor(c): return [c] * num elif len(c) == 0: #if edgecolor or facecolor is specified as 'none' return [[0,0,0,0]] * num elif iscolor(c[0]): return [c[0]] * num else: raise ValueError('unknown color format %s' % c)
def display_frame_coords(data, coords, window, vectors=None, ref=None, outlines=None, **kws): from grafico.imagine import ImageDisplay #FITSCubeDisplay, from obstools.aps import ApertureCollection fig, ax = plt.subplots() imd = ImageDisplay(ax, data) imd.connect() aps = ApertureCollection(coords=coords[:,::-1], radii=7, ec='darkorange', lw=1, ls='--', **kws) aps.axadd(ax) aps.annotate(color='orangered', size='small') if window: from matplotlib.patches import Rectangle from matplotlib.collections import PatchCollection llc = coords[:,::-1] - window/2 patches = [Rectangle(coo-window/2, window, window) for coo in llc] rcol = PatchCollection(patches, edgecolor='r', facecolor='none', lw=1, linestyle=':') ax.add_collection(rcol) if outlines is not None: from matplotlib.colors import to_rgba overlay = np.empty(data.shape+(4,)) overlay[...] = to_rgba('0.8', 0) overlay[...,-1][~outlines.mask] = 1 ax.hold(True) ax.imshow(overlay) if vectors is not None: if ref is None: 'cannot plot vectors without reference star' Y, X = coords[ref] V, U = vectors.T ax.quiver(X, Y, U, V, color='r', scale_units='xy', scale=1, alpha=0.6) return fig
def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): """ Parameters ---------- offset : pair of floats The offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : float The alpha transparency of the created shadow patch. Default is 0.3. http://matplotlib.1069221.n5.nabble.com/path-effects-question-td27630.html rho : float A scale factor to apply to the rgbFace color if `shadow_rgbFace` is not specified. Default is 0.3. **kwargs Extra keywords are stored and passed through to :meth:`AbstractPathEffect._update_gc`. """ super(SimplePatchShadow, self).__init__(offset) if shadow_rgbFace is None: self._shadow_rgbFace = shadow_rgbFace else: self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace) if alpha is None: alpha = 0.3 self._alpha = alpha self._rho = rho #: The dictionary of keywords to update the graphics collection with. self._gc = kwargs #: The offset transform object. The offset isn't calculated yet #: as we don't know how big the figure will be in pixels. self._offset_tran = mtransforms.Affine2D()
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = np.asarray(mcolors.to_rgba(colour)[:3]) # scale colour maxc = max(rgb) if maxc < 1.0 and maxc > 0: # scale colour scale = 1.0 / maxc rgb = rgb * scale # now decrease saturation total = rgb.sum() slack = 0 for x in rgb: slack += 1.0 - x # want to increase weight from total to weight # pick x s.t. slack * x == weight - total # x = (weight - total) / slack x = (weight - total) / slack rgb = [c + (x * (1.0 - c)) for c in rgb] return rgb
def figure_edit(axes, parent=None): """Edit matplotlib figure options""" sep = (None, None) # separator # Get / General xmin, xmax = map(float, axes.get_xlim()) ymin, ymax = map(float, axes.get_ylim()) general = [('Title', axes.get_title()), sep, (None, "<b>X-Axis</b>"), ('Min', xmin), ('Max', xmax), ('Label', axes.get_xlabel()), ('Scale', [axes.get_xscale(), 'linear', 'log']), sep, (None, "<b>Y-Axis</b>"), ('Min', ymin), ('Max', ymax), ('Label', axes.get_ylabel()), ('Scale', [axes.get_yscale(), 'linear', 'log']), sep, ('(Re-)Generate automatic legend', False), ] # Save the unit data xconverter = axes.xaxis.converter yconverter = axes.yaxis.converter xunits = axes.xaxis.get_units() yunits = axes.yaxis.get_units() # Sorting for default labels (_lineXXX, _imageXXX). def cmp_key(label): match = re.match(r"(_line|_image)(\d+)", label) if match: return match.group(1), int(match.group(2)) else: return label, 0 # Get / Curves linedict = {} for line in axes.get_lines(): label = line.get_label() if label == '_nolegend_': continue linedict[label] = line curves = [] def prepare_data(d, init): """Prepare entry for FormLayout. `d` is a mapping of shorthands to style names (a single style may have multiple shorthands, in particular the shorthands `None`, `"None"`, `"none"` and `""` are synonyms); `init` is one shorthand of the initial style. This function returns an list suitable for initializing a FormLayout combobox, namely `[initial_name, (shorthand, style_name), (shorthand, style_name), ...]`. """ # Drop duplicate shorthands from dict (by overwriting them during # the dict comprehension). name2short = {name: short for short, name in d.items()} # Convert back to {shorthand: name}. short2name = {short: name for name, short in name2short.items()} # Find the kept shorthand for the style specified by init. canonical_init = name2short[d[init]] # Sort by representation and prepend the initial value. return ([canonical_init] + sorted(short2name.items(), key=lambda short_and_name: short_and_name[1])) curvelabels = sorted(linedict, key=cmp_key) for label in curvelabels: line = linedict[label] color = mcolors.to_hex( mcolors.to_rgba(line.get_color(), line.get_alpha()), keep_alpha=True) ec = mcolors.to_hex(line.get_markeredgecolor(), keep_alpha=True) fc = mcolors.to_hex(line.get_markerfacecolor(), keep_alpha=True) curvedata = [ ('Label', label), sep, (None, '<b>Line</b>'), ('Line style', prepare_data(LINESTYLES, line.get_linestyle())), ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())), ('Width', line.get_linewidth()), ('Color (RGBA)', color), sep, (None, '<b>Marker</b>'), ('Style', prepare_data(MARKERS, line.get_marker())), ('Size', line.get_markersize()), ('Face color (RGBA)', fc), ('Edge color (RGBA)', ec)] curves.append([curvedata, label, ""]) # Is there a curve displayed? has_curve = bool(curves) # Get / Images imagedict = {} for image in axes.get_images(): label = image.get_label() if label == '_nolegend_': continue imagedict[label] = image imagelabels = sorted(imagedict, key=cmp_key) images = [] cmaps = [(cmap, name) for name, cmap in sorted(cm.cmap_d.items())] for label in imagelabels: image = imagedict[label] cmap = image.get_cmap() if cmap not in cm.cmap_d.values(): cmaps = [(cmap, cmap.name)] + cmaps low, high = image.get_clim() imagedata = [ ('Label', label), ('Colormap', [cmap.name] + cmaps), ('Min. value', low), ('Max. value', high), ('Interpolation', [image.get_interpolation()] + [(name, name) for name in sorted(image.iterpnames)])] images.append([imagedata, label, ""]) # Is there an image displayed? has_image = bool(images) datalist = [(general, "Axes", "")] if curves: datalist.append((curves, "Curves", "")) if images: datalist.append((images, "Images", "")) def apply_callback(data): """This function will be called to apply changes""" general = data.pop(0) curves = data.pop(0) if has_curve else [] images = data.pop(0) if has_image else [] if data: raise ValueError("Unexpected field") # Set / General (title, xmin, xmax, xlabel, xscale, ymin, ymax, ylabel, yscale, generate_legend) = general if axes.get_xscale() != xscale: axes.set_xscale(xscale) if axes.get_yscale() != yscale: axes.set_yscale(yscale) axes.set_title(title) axes.set_xlim(xmin, xmax) axes.set_xlabel(xlabel) axes.set_ylim(ymin, ymax) axes.set_ylabel(ylabel) # Restore the unit data axes.xaxis.converter = xconverter axes.yaxis.converter = yconverter axes.xaxis.set_units(xunits) axes.yaxis.set_units(yunits) axes.xaxis._update_axisinfo() axes.yaxis._update_axisinfo() # Set / Curves for index, curve in enumerate(curves): line = linedict[curvelabels[index]] (label, linestyle, drawstyle, linewidth, color, marker, markersize, markerfacecolor, markeredgecolor) = curve line.set_label(label) line.set_linestyle(linestyle) line.set_drawstyle(drawstyle) line.set_linewidth(linewidth) rgba = mcolors.to_rgba(color) line.set_alpha(None) line.set_color(rgba) if marker is not 'none': line.set_marker(marker) line.set_markersize(markersize) line.set_markerfacecolor(markerfacecolor) line.set_markeredgecolor(markeredgecolor) # Set / Images for index, image_settings in enumerate(images): image = imagedict[imagelabels[index]] label, cmap, low, high, interpolation = image_settings image.set_label(label) image.set_cmap(cm.get_cmap(cmap)) image.set_clim(*sorted([low, high])) image.set_interpolation(interpolation) # re-generate legend, if checkbox is checked if generate_legend: draggable = None ncol = 1 if axes.legend_ is not None: old_legend = axes.get_legend() draggable = old_legend._draggable is not None ncol = old_legend._ncol new_legend = axes.legend(ncol=ncol) if new_legend: new_legend.draggable(draggable) # Redraw figure = axes.get_figure() figure.canvas.draw() data = formlayout.fedit(datalist, title="Figure options", parent=parent, icon=get_icon('qt4_editor_options.svg'), apply=apply_callback) if data is not None: apply_callback(data)
def print_jpg(self, filename_or_obj, *args, dryrun=False, pil_kwargs=None, **kwargs): """ Write the figure to a JPEG file. Parameters ---------- filename_or_obj : str or path-like or file-like The file to write to. Other Parameters ---------------- quality : int, default: :rc:`savefig.jpeg_quality` The image quality, on a scale from 1 (worst) to 95 (best). Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality. This parameter is deprecated. optimize : bool, default: False Whether the encoder should make an extra pass over the image in order to select optimal encoder settings. This parameter is deprecated. progressive : bool, default: False Whether the image should be stored as a progressive JPEG file. This parameter is deprecated. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.Image.save` when saving the figure. These take precedence over *quality*, *optimize* and *progressive*. """ # Remove transparency by alpha-blending on an assumed white background. r, g, b, a = mcolors.to_rgba(self.figure.get_facecolor()) try: self.figure.set_facecolor(a * np.array([r, g, b]) + 1 - a) FigureCanvasAgg.draw(self) finally: self.figure.set_facecolor((r, g, b, a)) if dryrun: return if pil_kwargs is None: pil_kwargs = {} for k in ["quality", "optimize", "progressive"]: if k in kwargs: pil_kwargs.setdefault(k, kwargs[k]) if "quality" not in pil_kwargs: quality = pil_kwargs["quality"] = \ dict.__getitem__(mpl.rcParams, "savefig.jpeg_quality") if quality not in [0, 75, 95]: # default qualities. cbook.warn_deprecated( "3.3", name="savefig.jpeg_quality", obj_type="rcParam", addendum="Set the quality using " "`pil_kwargs={'quality': ...}`; the future default " "quality will be 75, matching the default of Pillow and " "libjpeg.") pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi)) # Drop alpha channel now. return (Image.fromarray(np.asarray(self.buffer_rgba())[..., :3]).save( filename_or_obj, format='jpeg', **pil_kwargs))
# If --metrics was used, add space and a subplot for the system metrics if has_system_metrics: figh += 4 nrows += 1 # Create the plot fig, axes = plt.subplots(nrows=nrows, sharex=True) axes = [axes] if nrows == 1 else axes # Add the benchmarks to the plot for i, benchmark_name in enumerate(benchmark_names): ax = axes[i] if is_detailed else axes[0] color = default_colors[i % len(default_colors)] name_to_color[benchmark_name] = color single_run_color = [colors.to_rgba(lighten_color(color, 0.7), 0.5)] # Filter the runs that belong to this benchmark item filtered_df = run_durations_df[run_durations_df["name"] == benchmark_name] # Plot runs into combined graph for success in [True, False]: data = filtered_df[filtered_df["success"] == success] if not data.empty: data.plot( ax=ax, kind="scatter", x="begin", y="duration", color=single_run_color, figsize=(figw, figh),
def gray_from_float_rgba(): return mcolors.to_rgba(0.4)
def plot_pcl_prediction(df, axis, probabilities_col=None, colors=None, xcol="x", ycol="y", zcol="z", use_plotly=False, inv_z=True): """Plots the pointcloud of a dataframe with interpolated coloring, dependent on probability estimates of corresponding classes. :param df: dataframe containing points and probability estimates. :type df: pandas.DataFrame :param axis: The matplotlib-axis the pointcloud should be plotted on :type axis: matplotlib.axes.Axes :param probabilities_col: Columns with probability estimates, defaults to None :type probabilities_col: list, optional :param colors: Colors associates with probability estimates, defaults to None :type colors: list, optional :param xcol: Column containing x-position, defaults to "x" :type xcol: str, optional :param ycol: Column containing y-position, defaults to "y" :type ycol: str, optional :param zcol: Column containing z-position, defaults to "z" :type zcol: str, optional :param use_plotly: Whether plotly should be used for plotting or not :type use_plotly: bool, optional :param inv_z: Whether the z-axis should be inverted. :type inv_z: bool, optional """ if probabilities_col is None: probabilities_col = [col for col in df.columns if "pred_" in col] if colors is None: colors = [ "blue", "orange", "green", "red", "purple", "brown", "pink", "gray", "olive", "cyan" ][:len(probabilities_col)] probarr = np.array(df[probabilities_col]) # linear interpolation between colors rgba_colors = np.array([to_rgba(color) for color in colors]) colorsarr = np.zeros(shape=(df.shape[0], 4)) for idx, col in enumerate(rgba_colors): colorsarr += (probarr[:, idx] * np.array([col] * df.shape[0]).T).T colorsarr = (colorsarr - np.min(colorsarr)) / (np.max(colorsarr) - np.min(colorsarr)) if use_plotly: layout = go.Layout(scene=dict(aspectmode="data"), showlegend=True) fig = go.Figure(layout=layout) predicted = np.argmax(df[probabilities_col].to_numpy(), axis=1) for idx, colname in enumerate(probabilities_col): selected = df[predicted == idx] selectedcolors = colorsarr[predicted == idx, :] fig.add_trace( go.Scatter3d(x=selected[xcol], y=selected[ycol], z=(-1 if inv_z else 1) * selected[zcol], opacity=1, mode='markers', marker=dict(size=1, color=selectedcolors, opacity=1), name=colname)) fig.show() else: # initialize 3d-plot axis.scatter(df[xcol], df[ycol], (-1 if inv_z else 1) * df[zcol], color=colorsarr, marker=".", s=0.7) for color, classname in zip(colors, probabilities_col): axis.add_line( plt.Line2D([0], [0], color=color, label=classname, lw=4)) legend = axis.legend(loc="lower left", title="Classes") axis.add_artist(legend) axis.grid(False) axis.set_axis_off() axis.set_xlim3d(-60, 60) axis.set_ylim3d(-60, 60) axis.set_zlim3d(-60, 60) axis.view_init(elev=40., azim=-120.) axis.set_xlabel('X') axis.set_ylabel('Y') axis.set_zlabel('Z')
mean_occ_df = occ_df.groupby('program').mean() std_occ_df = occ_df.groupby('program').std() fig = plt.figure(figsize=(7,5.4)) ax = plt.subplot(111) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) for mean, std in zip(mean_occ_df.iterrows(), std_occ_df.iterrows()): ax.errorbar(x=mean[1]['Occupancy'], y=mean[1]['B_factor'], xerr=std[1]['Occupancy'], yerr=std[1]['B_factor'], color=cols[mean[0]], fmt='o', ecolor=to_rgba(cols[mean[0]], 0.4), markersize=8, label=mean[0].replace('_',' ') ) # Dashed joining lines ax.plot([mean_occ_df.loc['buster', 'Occupancy'], mean_occ_df.loc['buster_superposed', 'Occupancy']], [mean_occ_df.loc['buster', 'B_factor'], mean_occ_df.loc['buster_superposed', 'B_factor']], linestyle='dashed', color=to_rgba('forestgreen', 0.5)) ax.plot([mean_occ_df.loc['refmac', 'Occupancy'], mean_occ_df.loc['refmac_superposed', 'Occupancy']], [mean_occ_df.loc['refmac', 'B_factor'],
def edge_color(self): if self.show_edge: return to_rgba(self.text_color, self.alpha) else: return None
segs = np.zeros((50, 100, 2), float) segs[:, :, 1] = ys segs[:, :, 0] = x # Mask some values to test masked array support: segs = np.ma.masked_where((segs > 50) & (segs < 60), segs) # We need to set the plot limits. ax = plt.axes() ax.set_xlim(x.min(), x.max()) ax.set_ylim(ys.min(), ys.max()) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used # See matplotlib.collections.LineCollection for more information colors = [ mcolors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color'] ] line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2), colors=colors, linestyle='solid') ax.add_collection(line_segments) ax.set_title('Line collection with masked arrays') plt.show()
#!/usr/bin/env python import nilearn from nilearn import plotting from nilearn import datasets from nilearn import surface from nilearn import image import matplotlib.pyplot as plt from matplotlib.colors import to_rgba import numpy as np VOIS = ['Action', 'LTM', 'Perception', 'Procedural', 'WM'] COLS = [list(to_rgba(x)) for x in \ ["#cc00cc", "#ff9900", "#ff3333", "#00cc33", "#00ccff"]] def load_vois(task): f = open("%s/vois.txt" % task) vois = {} for line in f.readlines(): name, coords = line.split()[:2] xyz = [int(x) for x in coords.split(",")] vois[name] = xyz return vois def load_individual_coords(task): vdict = {} for voi in VOIS:
def _map_scalar(self, x, alpha=None, bytes=False): y = to_rgba(BLUE, alpha) if x < 0.5 else to_rgba(RED, alpha) if bytes: y = np.floor(y * 255.).astype("int") return y
theta = np.linspace(0, 2*np.pi, nverts) xx = r * np.sin(theta) yy = r * np.cos(theta) spiral = list(zip(xx, yy)) # Make some offsets # Fixing random state for reproducibility rs = np.random.RandomState(19680801) xo = rs.randn(npts) yo = rs.randn(npts) xyo = list(zip(xo, yo)) # Make a list of colors cycling through the default series. colors = [colors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] fig, axes = plt.subplots(2, 2) fig.subplots_adjust(top=0.92, left=0.07, right=0.97, hspace=0.3, wspace=0.3) ((ax1, ax2), (ax3, ax4)) = axes # unpack the axes col = collections.LineCollection([spiral], offsets=xyo, transOffset=ax1.transData) trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0) col.set_transform(trans) # the points to pixels transform # Note: the first argument to the collection initializer # must be a list of sequences of x,y tuples; we have only # one sequence, but we still have to put it in a list.
def plot_results(hosts_filename="output_hosts_0.csv", event_filename="output_events_0.csv"): """Animate a particular epidemic simulation.""" state_colours = { "S": colors.to_rgba("green"), "E": colors.to_rgba("cyan"), "C": colors.to_rgba("blue"), "D": colors.to_rgba("orange"), "I": colors.to_rgba("red"), "R": colors.to_rgba("grey"), "Culled": colors.to_rgba("black"), } hosts_df = pd.read_csv(hosts_filename) events_df = pd.read_csv(event_filename) for i, x in enumerate(hosts_df.columns): if "timeEnter" in x: host_start_idx = i break host_points = np.zeros(len(hosts_df), dtype=[('position', float, 2), ('colour', float, 4)]) for index, host in hosts_df.iterrows(): host_points['position'][index] = (host['posX'], host['posY']) for name, timeEnter in host[host_start_idx:].iteritems(): if 0 in eval(timeEnter): state = name[9:] host_points['colour'][index] = state_colours[state] initial_colours = host_points['colour'][:] frame_rate = 30 animation_length = 5 frame_interval = max(events_df['time']) / (animation_length * frame_rate) nframes = animation_length * frame_rate + 1 fig = plt.figure(figsize=(7, 7)) ax = fig.add_axes([0, 0, 1, 1], frameon=False) ax.set_xlim(min(host_points['position'][:, 0]), max(host_points['position'][:, 0])) ax.set_xticks([]) ax.set_ylim(min(host_points['position'][:, 1]), max(host_points['position'][:, 1])) ax.set_yticks([]) scat = ax.scatter(host_points['position'][:, 0], host_points['position'][:, 1], c=host_points['colour']) time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes, weight="bold", fontsize=12, bbox=dict(facecolor='white', alpha=0.6)) global start_from_idx start_from_idx = 0 def init(): global start_from_idx start_from_idx = 0 host_points['colour'] = initial_colours new_time = 0 scat.set_color(host_points['colour']) time_text.set_text('time = %.3f' % new_time) return scat, time_text def update(frame_number): new_time = frame_number * frame_interval global start_from_idx row = events_df.iloc[start_from_idx] while row['time'] <= new_time: hostID = row['hostID'] new_state = row['newState'] host_points['colour'][hostID] = state_colours[new_state] start_from_idx += 1 if start_from_idx >= len(events_df): break row = events_df.iloc[start_from_idx] scat.set_color(host_points['colour']) time_text.set_text('time = %.3f' % new_time) return scat, time_text animation = FuncAnimation(fig, update, interval=1000 / frame_rate, frames=nframes, blit=True, repeat=False, init_func=init) plt.show()
where=monthly_sum != 0)) # define heatmaps for displaying monthly issue mix data cm_greens = cm.get_cmap('Greens', 15) # green = good (list reduction) cm_reds = cm.get_cmap('Reds', 15) # red = bad (list growth) cm_greens.set_over( '#FFFF00') # use yellow as default out of range green colour cm_reds.set_over('#FF00FF') # use purple as default out of range red colour # constrauct the colorbar from the heatmaps pos_cmap = cm.get_cmap('Greens_r', 15) neg_cmap = cm.get_cmap('Reds', 15) newcolors = np.vstack( (pos_cmap(np.linspace(0, 0.7, 15)), neg_cmap(np.linspace(0.3, 1, 15)))) combined_cmap = ListedColormap(newcolors, name='GreenRed') neutral = np.array(to_rgba('skyblue')) newcolors[ 14:16, :] = neutral # define neutral colour for balanced mix of issues for color in newcolors: # set transparency level (same as for plots) color[3] = 0.75 # set monthly time block separation space bar_spacing = 0.1 # figure settings #plt.style.use('seaborn-whitegrid') fig, ax = plt.subplots(3, 1, figsize=(15, 10), constrained_layout=False) plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
with _api.suppress_matplotlib_deprecation_warning(): with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] with mpl.rc_context(): copy.deepcopy(mpl.rcParams) with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True legend_color_tests = [ ('face', {'color': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'inherit', 'axes.facecolor': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')), ('edge', {'color': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')) ] legend_color_test_ids = [ 'same facecolor', 'inherited facecolor', 'different facecolor', 'same edgecolor', 'inherited edgecolor', 'different facecolor',
from PIL import Image, ImageTk try: box_icon = Image.open(r"icons\box_icon.png") except: import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import tkinter as tk from matplotlib.colors import to_rgba from itertools import product, combinations import mpl_toolkits.mplot3d.art3d as art3d mpl.style.use("fast") fig = plt.figure(figsize=(6, 6)) bgc = to_rgba("#F0F0F0") fig.patch.set_facecolor("black") fig.patch._alpha = 0.0 canvas = fig.canvas canvas.draw() ax = fig.add_subplot( projection="3d", facecolor=bgc, ) ax.view_init(19, -62) a = 0.96 xl, yl, zl = (-a, a), (-a, a), (-a, a) ax.set(xlim=xl, ylim=yl, zlim=zl) ax.patch._alpha = 0.0 ax.set_position([0, 0, 1, 1]) children = []
def visualize_accuracy(accr_dict, path, record_epoch): ''' Plot classification accuracy graph. It contains graph from several experimental versions to compare. Args: accr_dict (dict) : Classification accuracy. Each key denotes experimental version and each value contains 'test_num' lists. For example, if test_num is three, accr_dict['version_1] == [[accr_history_1], [accr_history_2], [accr_history_3]] accr_dict['version_2] == [[accr_history_1], [accr_history_2], [accr_history_3]] accr_dict['version_3] == [[accr_history_1], [accr_history_2], [accr_history_3]] tst_dloader (Dataloader) : Data loader for test set Return: classification accuracy ''' colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) # Sort colors by hue, saturation, value and name. by_hsv = sorted( (tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name) for name, color in colors.items()) sorted_names = [name for hsv, name in by_hsv] # Selected color color_names = ['steelblue', 'mediumseagreen', 'coral'] plt.switch_backend('agg') plt.figure(figsize=(12, 6)) total_len = len(accr_dict[list(accr_dict.keys())[0]][0]) x = range(0, record_epoch * total_len, record_epoch) for i, (exp_version, accr_hists) in enumerate(accr_dict.items()): max_accr = 0 color_val = colors[color_names[i]] # Find the one maximum accuracy among all tests in an experiment version # This value will be represented as a maximum accuracy of current experiment version for hist in accr_hists: cur_max_accr = max(hist) max_accr = cur_max_accr if cur_max_accr > max_accr else max_accr # plot for j, hist in enumerate(accr_hists): cur_max_accr = max(hist) max_accr = cur_max_accr if cur_max_accr > max_accr else max_accr label = 'M' + str(i + 1) + ': ' + str( round(max_accr, 6) * 100) + '%' if j == 0: plt.plot(x, hist, color_val, label=label) else: plt.plot(x, hist, color_val) plt.xlabel('Epoch') plt.ylabel('Accr') plt.legend(loc=4) plt.grid(True) plt.tight_layout() path = os.path.join(path, 'accr_model_compare.png') plt.savefig(path) plt.close()
def snap_plot(nets, size_scale=1 / 10, dims=(10, 10), savefigs=False): ''' ''' last_net = nets[-1] last_props = get_nodes_by_type(last_net, 'proposal') M = len(last_props) last_parts = get_nodes_by_type(last_net, 'participant') N = len(last_parts) pos = {} for ind in range(N): i = last_parts[ind] pos[i] = np.array([0, 2 * ind - N]) for ind in range(M): j = last_props[ind] pos[j] = np.array([1, 2 * N / M * ind - N]) if savefigs: counter = 0 length = 10 for net in nets: edges = get_edges_by_type(net, 'support') max_tok = np.max([net.edges[e]['tokens'] for e in edges]) E = len(edges) net_props = get_nodes_by_type(net, 'proposal') net_parts = get_nodes_by_type(net, 'participant') net_node_label = {} num_nodes = len([node for node in net.nodes]) node_color = np.empty((num_nodes, 4)) node_size = np.empty(num_nodes) edge_color = np.empty((E, 4)) cm = plt.get_cmap('Reds') cNorm = colors.Normalize(vmin=0, vmax=max_tok) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) net_cand = [ j for j in net_props if net.nodes[j]['status'] == 'candidate' ] for j in net_props: node_size[j] = net.nodes[j]['funds_requested'] * size_scale if net.nodes[j]['status'] == "candidate": node_color[j] = colors.to_rgba('blue') trigger = net.nodes[j]['trigger'] conviction = net.nodes[j]['conviction'] percent_of_trigger = " " + str( int(100 * conviction / trigger)) + '%' net_node_label[j] = str(percent_of_trigger) elif net.nodes[j]['status'] == "active": node_color[j] = colors.to_rgba('orange') net_node_label[j] = '' elif net.nodes[j]['status'] == "completed": node_color[j] = colors.to_rgba('green') net_node_label[j] = '' elif net.nodes[j]['status'] == "failed": node_color[j] = colors.to_rgba('gray') net_node_label[j] = '' elif net.nodes[j]['status'] == "killed": node_color[j] = colors.to_rgba('black') net_node_label[j] = '' for i in net_parts: node_size[i] = net.nodes[i]['holdings'] * size_scale / 10 node_color[i] = colors.to_rgba('red') net_node_label[i] = '' included_edges = [] for ind in range(E): e = edges[ind] tokens = net.edges[e]['tokens'] edge_color[ind] = scalarMap.to_rgba(tokens) if e[1] in net_cand: included_edges.append(e) iE = len(included_edges) included_edge_color = np.empty((iE, 4)) for ind in range(iE): e = included_edges[ind] tokens = net.edges[e]['tokens'] included_edge_color[ind] = scalarMap.to_rgba(tokens) else: plt.figure(figsize=dims) nx.draw(net, pos=pos, node_size=node_size, node_color=node_color, edge_color=included_edge_color, edgelist=included_edges, labels=net_node_label) plt.title('Tokens Staked by Partipants to Proposals') plt.tight_layout() plt.axis('on') plt.xticks([]) plt.yticks([]) if savefigs: plt.savefig('images/snap/' + str(counter) + '.png', bbox_inches='tight') counter = counter + 1 plt.show()
For more information on colors in matplotlib see * the :doc:`/tutorials/colors/colors` tutorial; * the `matplotlib.colors` API; * the :doc:`/gallery/color/color_demo`. """ import matplotlib.pyplot as plt from matplotlib import colors as mcolors colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) # Sort colors by hue, saturation, value and name. by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name) for name, color in colors.items()) sorted_names = [name for hsv, name in by_hsv] n = len(sorted_names) ncols = 4 nrows = n // ncols + 1 fig, ax = plt.subplots(figsize=(8, 5)) # Get height and width X, Y = fig.get_dpi() * fig.get_size_inches() h = Y / (nrows + 1) w = X / ncols for i, name in enumerate(sorted_names):
def get_rgb(x): rgba = to_rgba(x) return rgba[:3]
def volume_overlay(ax, opens, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence a sequence of opens closes : sequence a sequence of closes volumes : sequence a sequence of volumes width : int the bar width in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : `barCollection` The `barrCollection` added to the axes """ colorup = mcolors.to_rgba(colorup, alpha) colordown = mcolors.to_rgba(colordown, alpha) colord = {True: colorup, False: colordown} colors = [ colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1 ] delta = width / 2. bars = [((i - delta, 0), (i - delta, v), (i + delta, v), (i + delta, 0)) for i, v in enumerate(volumes) if v != -1] barCollection = PolyCollection( bars, facecolors=colors, edgecolors=((0, 0, 0, 1), ), antialiaseds=(0, ), linewidths=(0.5, ), ) ax.add_collection(barCollection) corners = (0, 0), (len(bars), max(volumes)) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
def has_alpha(x): return to_rgba(x) != to_rgba(x, 1)
def cc(arg): return mcolors.to_rgba(arg, alpha=0.6)
def _is_transparent(color): """Determine transparency from alpha.""" rgba = colors.to_rgba(color) return rgba[3] < .5
def cc(color, alpha=0.3): return mcolors.to_rgba(color, alpha=alpha)
def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75): """Represent the open, close as a bar line and high low range as a vertical line. NOTE: this code assumes if any value open, low, high, close is missing they all are missing Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence sequence of opening values highs : sequence sequence of high values lows : sequence sequence of low values closes : sequence sequence of closing values width : int size of open and close ticks in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : tuple (lineCollection, barCollection) """ _check_input(opens, highs, lows, closes) delta = width / 2. barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) for i, open, close in zip(xrange(len(opens)), opens, closes) if open != -1 and close != -1] rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] colorup = mcolors.to_rgba(colorup, alpha) colordown = mcolors.to_rgba(colordown, alpha) colord = {True: colorup, False: colordown} colors = [ colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1 ] useAA = 0, # use tuple here lw = 0.5, # and here rangeCollection = LineCollection( rangeSegments, colors=colors, linewidths=lw, antialiaseds=useAA, ) barCollection = PolyCollection( barVerts, facecolors=colors, edgecolors=colors, antialiaseds=useAA, linewidths=lw, ) minx, maxx = 0, len(rangeSegments) miny = min([low for low in lows if low != -1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(barCollection) return rangeCollection, barCollection
#!/usr/bin/python3 # coding: utf-8 # https://stackoverflow.com/questions/22408237/named-colors-in-matplotlib import matplotlib.pyplot as plt from matplotlib import colors as mcolors colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) # Sort colors by hue, saturation, value and name. by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name) for name, color in colors.items()) sorted_names = [name for hsv, name in by_hsv] n = len(sorted_names) ncols = 4 nrows = n // ncols fig, ax = plt.subplots(figsize=(12, 10)) # Get height and width X, Y = fig.get_dpi() * fig.get_size_inches() h = Y / (nrows + 1) w = X / ncols for i, name in enumerate(sorted_names): row = i % nrows col = i // nrows y = Y - (row * h) - h
def cc(arg): ''' Shorthand to convert 'named' colors to rgba format at 60% opacity. ''' return mcolors.to_rgba(arg, alpha=0.6)
def plot_positions_scatter(goal_object, runs_dir, img_dir, filename): """ :param goal_object :param runs_dir: :param img_dir: :param filename: """ dataset_states = load_dataset(runs_dir) dataset_states = dataset_states[[ 'goal_position', 'goal_angle', 'position', 'initial_position', 'initial_angle' ]] fig, axes = plt.subplots(ncols=2, figsize=(9.8, 4.8), constrained_layout=True, sharey='row') plt.ylim(-220, 220) # initial positions step_states = dataset_states.where(dataset_states.step == 0, drop=True) x, y = unpack(step_states.initial_position, 'axis') label = 'initial positions' goal_position = step_states.goal_position[0] goal_angle = step_states.goal_angle[0] radius = 8.5 axes[0].scatter(x, y, alpha=0.1, label=label, marker='o', s=(radius * np.pi)**2 / 5, facecolor=colors.to_rgba('tab:blue', alpha=0.1), edgecolor='none') axes[0].set_ylabel('y axis', fontsize=11) draw_docking_station(axes[0], goal_object) draw_marxbot(axes[0], goal_position, goal_angle, label='goal position') axes[0].set_xlim(-250, 250) axes[0].set_aspect('equal') axes[0].set_xlabel('x axis', fontsize=11) axes[0].legend() # final positions step_states = dataset_states.groupby("run").map( lambda x: x.isel(sample=[-1])) x, y = unpack(step_states.position, 'axis') goal_position = step_states.goal_position[0] goal_angle = step_states.goal_angle[0] axes[1].scatter(x, y, label='final positions', marker='o', s=(radius * np.pi)**2 / 5, facecolor=colors.to_rgba('tab:blue', alpha=0.1), edgecolor='none') draw_docking_station(axes[1], goal_object) draw_marxbot(axes[1], goal_position, goal_angle, label='goal position') axes[1].set_xlim(-250, 250) axes[1].set_aspect('equal') axes[1].set_xlabel('x axis', fontsize=11) axes[1].legend() save_visualisation(filename, img_dir)
def test_to_rgba(self): self.assertEqual(str(colors.to_rgba(self.color)), self.expectedRGBA)
def plot_surf_contours(surf_mesh, roi_map, axes=None, figure=None, levels=None, labels=None, colors=None, legend=False, cmap='tab20', title=None, output_file=None, **kwargs): """Plotting contours of ROIs on a surface, optionally over a statistical map. Parameters ---------- surf_mesh : str or list of two numpy.ndarray Surface mesh geometry, can be a file (valid formats are .gii or Freesurfer specific files such as .orig, .pial, .sphere, .white, .inflated) or a list of two Numpy arrays, the first containing the x-y-z coordinates of the mesh vertices, the second containing the indices (into coords) of the mesh faces. roi_map : str or numpy.ndarray or list of numpy.ndarray ROI map to be displayed on the surface mesh, can be a file (valid formats are .gii, .mgz, .nii, .nii.gz, or Freesurfer specific files such as .annot or .label), or a Numpy array with a value for each vertex of the surf_mesh. The value at each vertex one inside the ROI and zero inside ROI, or an integer giving the label number for atlases. axes : instance of matplotlib axes, None, optional The axes instance to plot to. The projection must be '3d' (e.g., `figure, axes = plt.subplots(subplot_kw={'projection': '3d'})`, where axes should be passed.). If None, uses axes from figure if available, else creates new axes. figure : instance of matplotlib figure, None, optional The figure instance to plot to. If None, uses figure of axes if available, else creates a new figure. levels : list of integers, or None, optional A list of indices of the regions that are to be outlined. Every index needs to correspond to one index in roi_map. If None, all regions in roi_map are used. labels : list of strings or None, or None, optional A list of labels for the individual regions of interest. Provide None as list entry to skip showing the label of that region. If None no labels are used. colors : list of matplotlib color names or RGBA values, or None, optional Colors to be used. legend : boolean, optional Whether to plot a legend of region's labels. Default=False. cmap : matplotlib colormap, str or colormap object, optional To use for plotting of the contours. Either a string which is a name of a matplotlib colormap, or a matplotlib colormap object. Default='tab20'. title : str, optional Figure title. output_file : str, or None, optional The name of an image file to export plot to. Valid extensions are .png, .pdf, .svg. If output_file is not None, the plot is saved to a file, and the display is closed. See Also -------- nilearn.datasets.fetch_surf_fsaverage : For surface data object to be used as background map for this plotting function. nilearn.plotting.plot_surf_stat_map : for plotting statistical maps on brain surfaces. nilearn.surface.vol_to_surf : For info on the generation of surfaces. """ if figure is None and axes is None: figure = plot_surf(surf_mesh, **kwargs) axes = figure.axes[0] if figure is None: figure = axes.get_figure() if axes is None: axes = figure.axes[0] if axes.name != '3d': raise ValueError('Axes must be 3D.') # test if axes contains Poly3DCollection, if not initialize surface if not axes.collections or not isinstance(axes.collections[0], Poly3DCollection): _ = plot_surf(surf_mesh, axes=axes, **kwargs) coords, faces = load_surf_mesh(surf_mesh) roi = load_surf_data(roi_map) if levels is None: levels = np.unique(roi_map) if colors is None: n_levels = len(levels) vmax = n_levels cmap = get_cmap(cmap) norm = Normalize(vmin=0, vmax=vmax) colors = [cmap(norm(color_i)) for color_i in range(vmax)] else: try: colors = [to_rgba(color, alpha=1.) for color in colors] except ValueError: raise ValueError('All elements of colors need to be either a' ' matplotlib color string or RGBA values.') if labels is None: labels = [None] * len(levels) if not (len(labels) == len(levels) and len(colors) == len(labels)): raise ValueError('Levels, labels, and colors ' 'argument need to be either the same length or None.') patch_list = [] for level, color, label in zip(levels, colors, labels): roi_indices = np.where(roi == level)[0] faces_outside = _get_faces_on_edge(faces, roi_indices) # Fix: Matplotlib version 3.3.2 to 3.3.3 # Attribute _facecolors3d changed to _facecolor3d in # matplotlib version 3.3.3 try: axes.collections[0]._facecolors3d[faces_outside] = color except AttributeError: axes.collections[0]._facecolor3d[faces_outside] = color if label and legend: patch_list.append(Patch(color=color, label=label)) # plot legend only if indicated and labels provided if legend and np.any([lbl is not None for lbl in labels]): figure.legend(handles=patch_list) if title: figure.suptitle(title) # save figure if output file is given if output_file is not None: figure.savefig(output_file) plt.close(figure) else: return figure
mfc='blue') line3 = axesList[3].plot(f, z, 'o', ls='-', color='blue', alpha=alpha, ms=3, markevery=.05, mec='None', mfc='red') # Plot fifth graph: # Create RGBA tuples for lines lcolor1 = colors.to_rgba('red', alpha=alpha) lcolor2 = colors.to_rgba('limegreen', alpha=alpha) lcolor3 = colors.to_rgba('blue', alpha=alpha) # Create RGBA tuples for markers mcolor1 = colors.to_rgba('limegreen', alpha=1.0) mcolor2 = colors.to_rgba('blue', alpha=0.4) mcolor3 = colors.to_rgba('red', alpha=0.15) # Plot x, y, and z lines and markers- the lines have the same # transparency level, but the markers vary in alpha value line1 = axesList[4].plot(f, x, 'o', ls='-', color=lcolor1,
def test_default_color(self): assert self.state.frame_color == settings.BACKGROUND_COLOR assert self.state.edge_color == to_rgba(settings.FOREGROUND_COLOR, self.state.alpha)
with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] with mpl.rc_context(): copy.deepcopy(mpl.rcParams) with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True legend_color_tests = [('face', { 'color': 'r' }, mcolors.to_rgba('r')), ('face', { 'color': 'inherit', 'axes.facecolor': 'r' }, mcolors.to_rgba('r')), ('face', { 'color': 'g', 'axes.facecolor': 'r' }, mcolors.to_rgba('g')), ('edge', { 'color': 'r' }, mcolors.to_rgba('r')), ('edge', { 'color': 'inherit', 'axes.edgecolor': 'r' }, mcolors.to_rgba('r')),
# ---------------------------------------------------------------------------- # Title: Scientific Visualisation - Python & Matplotlib # Author: Nicolas P. Rougier # License: BSD # ---------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from matplotlib.ticker import NullFormatter X = np.random.uniform(0, 1, 1000) Y = np.random.uniform(0, 1, 1000) S = np.sqrt((X - 0.5)**2 + (Y - 0.5)**2) C = np.ones((1000, 4)) * colors.to_rgba("C0") C[S > 0.5] = colors.to_rgba("C1") figure = plt.figure(figsize=(8, 4)) # Linear scale ax = plt.subplot(1, 2, 1, xlim=(0, 1), ylim=(0, 1)) ax.scatter(X, Y, s=25, facecolor=C, edgecolor="none", alpha=0.5) T = np.linspace(0, 2 * np.pi, 100) X2 = 0.5 + 0.5 * np.cos(T) Y2 = 0.5 + 0.5 * np.sin(T) ax.plot(X2, Y2, color="black", linestyle="--", linewidth=0.75) # ax = plt.subplot(1, 2, 2, xlim=(0.01, 0.99), ylim=(0.01, 0.99)) ax.set_xscale("logit") ax.set_yscale("logit") ax.scatter(X, Y, s=25, facecolor=C, edgecolor="none", alpha=0.5)
def apply_callback(data): """This function will be called to apply changes""" general = data.pop(0) curves = data.pop(0) if has_curve else [] images = data.pop(0) if has_image else [] if data: raise ValueError("Unexpected field") # Set / General (title, xmin, xmax, xlabel, xscale, ymin, ymax, ylabel, yscale, generate_legend) = general if axes.get_xscale() != xscale: axes.set_xscale(xscale) if axes.get_yscale() != yscale: axes.set_yscale(yscale) axes.set_title(title) axes.set_xlim(xmin, xmax) axes.set_xlabel(xlabel) axes.set_ylim(ymin, ymax) axes.set_ylabel(ylabel) # Restore the unit data axes.xaxis.converter = xconverter axes.yaxis.converter = yconverter axes.xaxis.set_units(xunits) axes.yaxis.set_units(yunits) axes.xaxis._update_axisinfo() axes.yaxis._update_axisinfo() # Set / Curves for index, curve in enumerate(curves): line = linedict[curvelabels[index]] (label, linestyle, drawstyle, linewidth, color, marker, markersize, markerfacecolor, markeredgecolor) = curve line.set_label(label) line.set_linestyle(linestyle) line.set_drawstyle(drawstyle) line.set_linewidth(linewidth) rgba = mcolors.to_rgba(color) line.set_alpha(None) line.set_color(rgba) if marker is not 'none': line.set_marker(marker) line.set_markersize(markersize) line.set_markerfacecolor(markerfacecolor) line.set_markeredgecolor(markeredgecolor) # Set / Images for index, image_settings in enumerate(images): image = imagedict[imagelabels[index]] label, cmap, low, high, interpolation = image_settings image.set_label(label) image.set_cmap(cm.get_cmap(cmap)) image.set_clim(*sorted([low, high])) image.set_interpolation(interpolation) # re-generate legend, if checkbox is checked if generate_legend: draggable = None ncol = 1 if axes.legend_ is not None: old_legend = axes.get_legend() draggable = old_legend._draggable is not None ncol = old_legend._ncol new_legend = axes.legend(ncol=ncol) if new_legend: new_legend.draggable(draggable) # Redraw figure = axes.get_figure() figure.canvas.draw()
def cc(arg, alpha=.6): """ Shorthand to convert 'named' colors to rgba format with opacity. """ return mcolors.to_rgba(arg, alpha=alpha)
_deep_copy = copy.deepcopy(mpl.rcParams) # real test is that this does not raise assert validate_bool_maybe_none(None) is None assert validate_bool_maybe_none("none") is None with pytest.raises(ValueError): validate_bool_maybe_none("blah") with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True legend_color_tests = [ ('face', {'color': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'inherit', 'axes.facecolor': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')), ('edge', {'color': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')) ] legend_color_test_ids = [ 'same facecolor', 'inherited facecolor', 'different facecolor', 'same edgecolor', 'inherited edgecolor', 'different facecolor',
def test_2d_to_rgba(): color = np.array([0.1, 0.2, 0.3]) rgba_1d = mcolors.to_rgba(color.reshape(-1)) rgba_2d = mcolors.to_rgba(color.reshape((1, -1))) assert rgba_1d == rgba_2d