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]) r, g, b = colorConverter.to_rgb(line.get_color()) color = gtk.gdk.Color(*[int(val * 65535) for val in r, g, b]) button = self.wtree.get_widget("colorbutton_linestyle") button.set_color(color) r, g, b = colorConverter.to_rgb(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val * 65535) for val in r, g, b]) 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 ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency """ r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,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,), ) corners = (0, 0), (len(bars), max(volumes)) ax.update_datalim(corners) ax.autoscale_view() return barCollection
def _compute_colors(self, array_x, array_y): # on calcule le maximum absolu de toutes valeurs pour former un carré abs_maximum = max([max(map(abs,array_x)), max(map(abs,array_y))]) diagonal_length = norm(array([abs_maximum, abs_maximum])) # longueur de la projection diag = array([diagonal_length, diagonal_length]) anti_diag = array([-diagonal_length, diagonal_length]) # on instancie le gradient de couleur sur le modèle de couleur du centre linear_normalizer = mpl.colors.Normalize(vmin=-abs_maximum, vmax=abs_maximum) log_normalizer = mpl.colors.SymLogNorm(abs_maximum/5, vmin=-abs_maximum, vmax=abs_maximum) r_to_b_gradient = cm.ScalarMappable(norm=linear_normalizer, cmap=redtoblue) # on calcule le produit scalaire de chaque valeur avec la diagonale # ensuite, on calcule la couleur à partir de la valeur de la projection sur la diagonale hex_color_values = [] for i, x in enumerate(array_x): # on calcule les produits scalaire du point avec la diagonale et l'antidiagonale scal_p_diag = dot(array([array_x[i], array_y[i]]), diag) / diagonal_length scal_p_antidiag = dot(array([array_x[i], array_y[i]]), anti_diag) / diagonal_length #on calcule le gradient de couleur sur la diagonale on_diag_color = colorConverter.to_rgb(r_to_b_gradient.to_rgba(scal_p_diag)) # puis on utilise cette couleur (en rgb) pour définir un gradient, dont la valeur sera estimée # sur l'antidiagonale on_diag_gradient = make_white_gradient(on_diag_color, log_normalizer) final_color = on_diag_gradient.to_rgba(scal_p_antidiag) #on traduit en HEX hex_color_values.append(rgb2hex(colorConverter.to_rgb(final_color))) return hex_color_values, abs_maximum
def add_bars(self, colorup='g', colordown='r', alpha=0.5, width=1): r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = {True: colorup, False: colordown} colors = [colord[open<close] for open, close in zip(self.opens, self.closes)] delta = width/2.0 bars = [((x-delta, 0), (x-delta, y), (x+delta, y), (x+delta, 0)) for x, y in zip(self.dates, self.volumes)] barCollection = PolyCollection(bars, facecolors = colors) #self.ax.step(self.dates, self.volumes) #self.ax.add_collection(barCollection) #self.ax.bar(self.dates, self.volumes) #self.ax.plot(self.dates, self.volumes) self.ax.fill_between(self.dates, self.volumes, alpha=0.5) xmin, xmax = self.ax.get_xlim() ys = [y for x, y in zip(self.dates, self.volumes) if xmin<=x<=xmax] if ys: self.ax.set_ylim([0, max(ys)*10]) for tick in self.ax.get_yticklabels(): tick.set_visible(False)
def plot(self, widget, width=0.6, colorup='r', colordown='g', lc='k', alpha=1): """docstring for plot""" delta = self.width/2. barVerts = [((i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open)) for i, open, close in zip(xrange(len(self.data)), self.data.open, self.data.close) if open != -1 and close != -1] rangeSegments = [((i, low), (i, high)) for i, low, high in zip( xrange(len(self.data)), self.data.low, self.data.high) if low != -1] r, g, b = colorConverter.to_rgb(self.colorup) colorup = r, g, b, self.alpha r, g, b = colorConverter.to_rgb(self.colordown) colordown = r, g, b, self.alpha colord = { True: colorup, False: colordown, } colors = [colord[open < close] for open, close in zip(self.data.open, self.data.close) if open != -1 and close != -1] assert(len(barVerts) == len(rangeSegments)) useAA = 0, # use tuple here lw = 0.5, # and here r, g, b = colorConverter.to_rgb(self.lc) linecolor = r, g, b, self.alpha lineCollection = LineCollection(rangeSegments, colors=(linecolor,), linewidths=lw, antialiaseds=useAA, zorder=0) barCollection = PolyCollection(barVerts, facecolors=colors, edgecolors=colors, antialiaseds=useAA, linewidths=lw, zorder=1) #minx, maxx = 0, len(rangeSegments) #miny = min([low for low in self.data.low if low !=-1]) #maxy = max([high for high in self.data.high if high != -1]) #corners = (minx, miny), (maxx, maxy) #ax.update_datalim(corners) widget.autoscale_view() # add these last widget.add_collection(barCollection) widget.add_collection(lineCollection) #ax.plot(self.data.close, color = 'y') #lineCollection, barCollection = None, None return lineCollection, barCollection
def plot(self, widget, data, width=0.6, colorup='r', colordown='g', lc='k', alpha=1): if self.lineCollection: self.lineCollection.remove() if self.barCollection: self.barCollection.remove() self.set_yrange(data.low.values, data.high.values) self.data = data """docstring for plot""" delta = self.width / 2. barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) for i, open, close in zip(range(len(self.data)), self.data.open, self.data.close) if open != -1 and close != -1] rangeSegments = [((i, low), (i, high)) for i, low, high in zip(range(len(self.data)), self.data.low, self.data.high) if low != -1] r, g, b = colorConverter.to_rgb(self.colorup) colorup = r, g, b, self.alpha r, g, b = colorConverter.to_rgb(self.colordown) colordown = r, g, b, self.alpha colord = { True: colorup, False: colordown, } colors = [colord[open < close] for open, close in zip(self.data.open, self.data.close) if open != -1 and close != -1] assert(len(barVerts) == len(rangeSegments)) useAA = 0, # use tuple here lw = 0.5, # and here r, g, b = colorConverter.to_rgb(self.lc) linecolor = r, g, b, self.alpha self.lineCollection = LineCollection(rangeSegments, colors=(linecolor,), linewidths=lw, antialiaseds=useAA, zorder=0) self.barCollection = PolyCollection(barVerts, facecolors=colors, edgecolors=colors, antialiaseds=useAA, linewidths=lw, zorder=1) widget.autoscale_view() # add these last widget.add_collection(self.barCollection) widget.add_collection(self.lineCollection) return self.lineCollection, self.barCollection
def candlestick2(ax, opens, closes, highs, lows, 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. ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency return value is lineCollection, barCollection """ # note this code assumes if any value open, close, low, high is # missing they all are missing delta = width / 2.0 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] r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown} colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] assert len(barVerts) == len(rangeSegments) useAA = (0,) # use tuple here lw = (0.5,) # and here rangeCollection = LineCollection(rangeSegments, colors=((0, 0, 0, 1),), linewidths=lw, antialiaseds=useAA) barCollection = PolyCollection( barVerts, facecolors=colors, edgecolors=((0, 0, 0, 1),), 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(barCollection) ax.add_collection(rangeCollection) return rangeCollection, barCollection
def create_colormap(col1, col2): c1 = colorConverter.to_rgb(col1) c2 = colorConverter.to_rgb(col2) cdict = { 'red': ((0.,c1[0], c1[0]),(1.,c2[0], c2[0])), 'green': ((0.,c1[1], c1[1]),(1.,c2[1], c2[1])), 'blue': ((0.,c1[2], c1[2]),(1.,c2[2], c2[2])) } return LinearSegmentedColormap('custom', cdict, 256)
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 ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency """ r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, alpha colord = {True: colorup, False: colordown} colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] right = width / 2.0 left = -width / 2.0 bars = [((left, 0), (left, v), (right, v), (right, 0)) for v in volumes if v != -1] sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = Affine2D().scaled(sx, sy) offsetsBars = [(i, 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,), offsets=offsetsBars, transOffset=ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in volumes if v != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
def _to_rgb(c): """ Convert color *c* to a numpy array of *RGB* handling exeption Parameters ---------- c: Matplotlib color same as *color* in *colorAlpha_to_rgb* output ------ rgbs: list of numpy array list of c converted to *RGB* array """ if(getattr(c, '__iter__', False) == False): #if1: if c is a single element (number of string) rgbs = [np.array(cC.to_rgb(c)),] #list with 1 RGB numpy array else: #if1, else: if is more that one element try: #try1: check if c is numberic or not np.array(c) + 1 except (TypeError, ValueError): #try1: if not numerics is not (only) RGB or RGBA colors #convert the list/tuble/array of colors into a list of numpy arrays of RGB rgbs = [np.array( cC.to_rgb(i)) for i in c] except Exception as e: #try1: if any other exception raised print("Unexpected error: {}".format(e)) raise e #raise it else: #try1: if the colors are all numberics arrc = np.array(c) #convert c to a numpy array arrcsh = arrc.shape #shape of the array if len(arrcsh)==1: #if2: if 1D array given if(arrcsh[0]==3 or arrcsh[0]==4): #if3: if RGB or RBGA rgbs = [np.array(cC.to_rgb(c)),] #list with 1 RGB numpy array else: #if3, else: the color cannot be RBG or RGBA raise ValueError('Invalid rgb arg "{}"'.format(c)) #end if3 elif len(arrcsh)==2: #if2, else: if 2D array if(arrcsh[1]==3 or arrcsh[1]==4): #if4: if RGB or RBGA rgbs = [np.array(cC.to_rgb(i)) for i in c] #list with RGB numpy array else: #if4, else: the color cannot be RBG or RGBA raise ValueError('Invalid list or array of rgb') #end if4 else: #if2, else: if more dimention raise ValueError('The rgb or rgba values must be contained in a 1D or 2D list or array') #end if2 #end try1 #end if1 return rgbs
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 """ r, g, b = colorConverter.to_rgb(colorup) colorup = r, g, b, alpha r, g, b = colorConverter.to_rgb(colordown) colordown = r, g, b, 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.0 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 volume_overlay3(ax, quotes, colorup='k', colordown='r', width=4, alpha=1.0): """ Add a volume overlay to the current axes. quotes is a list of (d, open, close, high, low, volume) and close-open is used to determine the color of the bar kwarg width : the bar width in points colorup : the color of the lines where close1 >= close0 colordown : the color of the lines where close1 < close0 alpha : bar transparency """ r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = { True : colorup, False : colordown, } dates, opens, closes, highs, lows, volumes = zip(*quotes) colors = [colord[close1>=close0] for close0, close1 in zip(closes[:-1], closes[1:]) if close0!=-1 and close1 !=-1] colors.insert(0,colord[closes[0]>=opens[0]]) right = width/2.0 left = -width/2.0 bars = [ ( (left, 0), (left, volume), (right, volume), (right, 0)) for d, open, close, high, low, volume in quotes] sx = ax.figure.dpi * (1.0/72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height barTransform = Affine2D().scale(sx,sy) dates = [d for d, open, close, high, low, volume in quotes] offsetsBars = [(d, 0) for d in dates] useAA = 0, # use tuple here lw = 0.5, # and here barCollection = PolyCollection(bars, facecolors = colors, edgecolors = ( (0,0,0,1), ), antialiaseds = useAA, linewidths = lw, offsets = offsetsBars, transOffset = ax.transData, ) barCollection.set_transform(barTransform) minpy, maxx = (min(dates), max(dates)) miny = 0 maxy = max([volume for d, open, close, high, low, volume in quotes]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.add_collection(barCollection) ax.autoscale_view() return barCollection
def plot_hmm(means_, transmat, covars, initProbs, axes=None, clr=None, transition_arrows=True): if axes != None: axes(axes) # f, axes = subplots(2)#,sharex=True, sharey=True) # sca(axes[0]) global annotations annotations = [] global means means = [] colors = clr # color_map = colors #[colorConverter.to_rgb(colors[i]) for i in range(len(means_))] for i, mean in enumerate(means_): # print_n_flush( "MEAN:", tuple(mean)) means.append(scatter(*tuple(mean), color=colorConverter.to_rgb(colors[i]), picker=10, label="State%i" % i)) annotate(s="%d" % i, xy=mean, xytext=(-10, -10), xycoords="data", textcoords="offset points", alpha=1, bbox=dict(boxstyle='round,pad=0.2', fc=colorConverter.to_rgb(colors[i]), alpha=0.3)) # gca().add_patch(Ellipse(xy = means_[i], width = np.diag(covars[i])[0], height = np.diag(covars[i])[1], # alpha=.15, color=colorConverter.to_rgb(colors[i]))) plot_cov_ellipse(covars[i], mean, alpha=.15, color=colorConverter.to_rgb(colors[i])) x0, y0 = mean prob_string = "P(t0)=%f" % initProbs[i] for j, p in enumerate(transmat[i]): xdif = 10 ydif = 5 s = "P(%d->%d)=%f" % (i, j, p) # print_n_flush( "State%d: %s" % (i, s)) prob_string = "%s\n%s" % (prob_string, s) if transition_arrows: if i != j: x1, y1 = means_[j] # if transmat[i][j] is too low, we get an underflow here # q = quiver([x0], [y0], [x1-x0], [y1-y0], alpha = 10000 * (transmat[i][j]**2), alpha = 10 ** -300 if p > 10 ** -100: alpha = (100 * p) ** 2 q = quiver([x0], [y0], [x1 - x0], [y1 - y0], alpha=1 / log(alpha), scale_units='xy', angles='xy', scale=1, width=0.005, label="P(%d->%d)=%f" % (i, j, p)) # legend() annotations.append(annotate(s=prob_string, xy=mean, xytext=(0, 10), xycoords="data", textcoords="offset points", alpha=1, bbox=dict(boxstyle='round,pad=0.2', fc=colorConverter.to_rgb(colors[i]), alpha=0.3), picker=True, visible=False)) # print_n_flush( "State%i is %s" % (i, colors[i])) cid = gcf().canvas.mpl_connect('pick_event', on_pick)
def color_to_hex(color): """Convert matplotlib color code to hex color code""" if color is None or colorConverter.to_rgba(color)[3] == 0: return 'none' else: rgb = colorConverter.to_rgb(color) return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
def add_aliasing_edges(G, only_states, belief_mdp, pomdp): # @UnusedVariable for s1 in only_states: for s2 in only_states: if s1 == s2: continue obs1 = pomdp.get_observations_dist_given_belief(s1) obs2 = pomdp.get_observations_dist_given_belief(s2) can_distinguish = len(set(obs1) & set(obs2)) == 0 # if not len(obs1) == 0 or not len(obs2) == 0: # print('not deterministic, %s , %s , %s , # %s ' % (s1, obs1, s2, obs2)) # continue if not can_distinguish: # aliasing! G.add_edge(s1, s2) G.edge[s1][s2]['type'] = 'aliasing' G.edge[s1][s2]['edge_color'] = colorConverter.to_rgb('y') G.edge[s1][s2]['edge_style'] = 'dotted' return G
def pastel(colour, weight=2.4): ''' Convert colour into a nice pastel shade ''' rgb = asarray(colorConverter.to_rgb(colour)) # 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 = sum(rgb) 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 from_list(name, colors, N=256, gamma=1.0): """ Make a linear segmented colormap with *name* from a sequence of *colors* which evenly transitions from colors[0] at val=0 to colors[-1] at val=1. *N* is the number of rgb quantization levels. Alternatively, a list of (value, color) tuples can be given to divide the range unevenly. """ if not cbook.iterable(colors): raise ValueError('colors must be iterable') if cbook.iterable(colors[0]) and len(colors[0]) == 2 and \ not cbook.is_string_like(colors[0]): # List of value, color pairs vals, colors = zip(*colors) else: vals = np.linspace(0., 1., len(colors)) cdict = dict(red=[], green=[], blue=[]) for val, color in zip(vals, colors): r,g,b = colorConverter.to_rgb(color) cdict['red'].append((val, r, r)) cdict['green'].append((val, g, g)) cdict['blue'].append((val, b, b)) return MixedAlphaColormap(name, cdict, N, gamma)
def gradient(cmin, cmax): if isinstance(cmin, str): cmin = colorConverter.to_rgb(cmin) if isinstance(cmax, str): cmax = colorConverter.to_rgb(cmax) cdict = { 'red': [(0, 0, cmin[0]), (1, cmax[0], 1)], 'green': [(0, 0, cmin[1]), (1, cmax[1], 1)], 'blue': [(0, 0, cmin[2]), (1, cmax[2], 1)] } return mpl.colors.LinearSegmentedColormap('cmap', cdict, N=1000)
def __init__(self, label=None, marker="o", markersize=10, color="blue", saturation=1, opaqcity=1, zorder=0): self.label = label self.marker = marker self.markersize = markersize self.color_rgb = colorConverter.to_rgb(color) self.saturation = saturation self.opaqcity = opaqcity self.zorder = zorder
def get_selection_box_colour(series): """ Returns a colour (as an RGB tuple) that will be visible against the background of the subplot. """ subplot = series.get_subplot() bkgd_col = colorConverter.to_rgb(subplot.get_mpl_axes().get_axis_bgcolor()) return tuple([1.0 - c for c in bkgd_col])
def _register_cmap_transparent(name, color): """Create a color map from a given color to transparent.""" from matplotlib.colors import colorConverter, LinearSegmentedColormap red, green, blue = colorConverter.to_rgb(color) cdict = {'red': ((0, red, red), (1, red, red)), 'green': ((0, green, green), (1, green, green)), 'blue': ((0, blue, blue), (1, blue, blue)), 'alpha': ((0, 0, 0), (1, 1, 1))} cmap = LinearSegmentedColormap(name, cdict) _plt.cm.register_cmap(cmap=cmap)
def colorAlpha_to_rgb(colors, alpha, bg='w'): """ Given a Matplotlib color and a value of alpha, it returns a RGB color which mimic the RGBA colors on the given background Parameters ---------- colors: Matplotlib color (documentation from matplotlib.colors.colorConverter.to_rgb), list/tuple/numpy array of colors Can be an *RGB* or *RGBA* sequence or a string in any of several forms: 1) a letter from the set 'rgbcmykw' 2) a hex color string, like '#00FFFF' 3) a standard name, like 'aqua' 4) a float, like '0.4', indicating gray on a 0-1 scale if *color* is *RGBA*, the *A* will simply be discarded. alpha: float [0,1] or list/tuple/numpy array with len(colors) elements Value of alpha to mimic. bg: Matplotlib color (optional, default='w') Color of the background. Can be of any type shown in *color* output ------ rgb: *RGB* color example ------- import mimic_alpha as ma print(ma.colorAlpha_to_rgb('r', 0.5)) >>> [array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(['r', 'g'], 0.5)) >>> [array([ 1. , 0.5, 0.5]), array([ 0.5 , 0.75, 0.5 ])] print(ma.colorAlpha_to_rgb(['r', 'g'], [0.5, 0.3])) >>> [array([ 1. , 0.5, 0.5]), array([ 0.7 , 0.85, 0.7 ])] print(ma.colorAlpha_to_rgb(['r', [1,0,0]], 0.5)) >>> [array([ 1. , 0.5, 0.5]), array([ 1. , 0.5, 0.5])] print( ma.colorAlpha_to_rgb([[0,1,1], [1,0,0]], 0.5) ) >>> [array([ 0.5, 1. , 1. ]), array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5)) >>> [array([ 0.5, 1. , 1. ]), array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5, bg='0.5')) >>> [array([ 0.25, 0.75, 0.75]), array([ 0.75, 0.25, 0.25])] """ colors = _to_rgb(colors) #convert the color and save in a list of np arrays bg = np.array(cC.to_rgb(bg)) #convert the background #check if alpha has 1 or len(colors) elements and return a list of len(color) alpha alpha = _check_alpha(alpha, len(colors)) #interpolate between background and color rgb = [(1.-a) * bg + a*c for c,a in zip(colors, alpha)] return rgb
def export_color(color): """Convert matplotlib color code to hex color or RGBA color""" if color is None or colorConverter.to_rgba(color)[3] == 0: return 'none' elif colorConverter.to_rgba(color)[3] == 1: rgb = colorConverter.to_rgb(color) return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb)) else: c = colorConverter.to_rgba(color) return "rgba(" + ", ".join(str(int(np.round(val * 255))) for val in c[:3])+', '+str(c[3])+")"
def plot_hit_matrix(hit_matrix, k, m, fold, kmers, virus_family, sequence_type, project_path): background_colors = { 'white' : np.array([255,255,255]).reshape(1,3)/255., 'black' : np.array([0,0,0]).reshape(1,3)/255., 'grey' : np.array([38,38,38]).reshape(1,3)/255., 'darkgrey' : np.array([18,18,18]).reshape(1,3)/255., 'offwhite' : np.array([235,235,235]).reshape(1,3)/255., } kmer_colors = ['red','green','blue','purple','cyan','orange','magenta','black','hotpink'] (num_proteins,C,ig) = hit_matrix.shape C = C-1 V = min([9,len(kmers)]) data = np.zeros((num_proteins,C,3),dtype='float') for i in range(V): data += hit_matrix[:,1:,i:i+1] * np.array(list(convert.to_rgb(kmer_colors[i]))) idx = (hit_matrix[:,0,0]==1).nonzero()[0] data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1) * background_colors['white'] idx = (hit_matrix[:,0,0]==2).nonzero()[0] data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1) * background_colors['offwhite'] # idx = (hit_matrix[:,0,0]==3).nonzero()[0] # data[idx,:,:] = data[idx,:,:] + (1-(data[idx,:,:].sum(2)>0)).reshape(idx.size,C,1)*color_scheme['white'] fig = plot.figure() im = fig.add_subplot(111) im.set_position([0.03,0.07,0.80,0.88]) im.imshow(data,aspect='auto',interpolation='nearest') im.axis([0,hit_matrix.shape[1]-1,0,hit_matrix.shape[0]]) im.set_xticks([0,hit_matrix.shape[1]-1]) im.set_xticklabels((0,1)) im.set_xlabel('Relative location') y_labels = ('Plant','Animal') y_label_loc = [] for c in np.unique(hit_matrix[:,0,0]): y_label_loc.append(int(np.mean((hit_matrix[:,0,0]==c).nonzero()[0]))) im.set_yticks(y_label_loc) im.set_yticklabels(y_labels, rotation=90) for line in im.get_yticklines(): line.set_markersize(0) im.set_title('k = %d, m = %d' % (k,m)) # a figtext bbox for legend kmer_locs = np.linspace(0.5+V/2*0.04,0.5-V/2*0.04,V) for kidx in range(V): kmer = kmers[kidx] try: plot.figtext(0.84, kmer_locs[kidx], kmer, fontsize=9, color=kmer_colors[kidx], horizontalalignment='left', verticalalignment='center') except IndexError: pdb.set_trace() fname = project_path + 'fig/%s_%s_kmer_visualization_%d_%d_%d.pdf' % (virus_family, sequence_type, k, m, fold) fig.savefig(fname,dpi=(300),format='pdf')
def create_colormap(*args): col = [colorConverter.to_rgb(c) for c in args] step = 1.0 / (len(col) - 1) cdict = { 'red': [[i * step, col[i][0], col[i][0]] for i in range(len(col))], 'green': [[i * step, col[i][1], col[i][1]] for i in range(len(col))], 'blue': [[i * step, col[i][2], col[i][2]] for i in range(len(col))] } return LinearSegmentedColormap('custom', cdict, 256)
def _register_cmap_transparent(name, color): """Create a color map from a given color to transparent.""" from matplotlib.colors import colorConverter, LinearSegmentedColormap red, green, blue = colorConverter.to_rgb(color) cdict = { 'red': ((0, red, red), (1, red, red)), 'green': ((0, green, green), (1, green, green)), 'blue': ((0, blue, blue), (1, blue, blue)), 'alpha': ((0, 0, 0), (1, 1, 1)) } cmap = LinearSegmentedColormap(name, cdict) plt.cm.register_cmap(cmap=cmap)
def show(self): self.fr1=Frame(self.fig.fr_curves, padx=3, pady=3) self.fr1.pack(side=TOP) l=Label(self.fr1, text="%s(%s)"%(self.y, self.x)); l.pack(side=LEFT) Button(self.fr1, text="Del", command=self.destroy).pack(side=LEFT) # self.line, = self.fig.ax.plot(self.sode[self.x], self.sode[self.y],'.-',label="%s(%s)"%(self.y, self.x)) self.line, = self.fig.ax.plot(self.sode[self.x], self.sode[self.y],label="%s(%s)"%(self.y, self.x)) self.fr1["bg"] = rgb2hex(colorConverter.to_rgb(self.line.get_color())) # self.ax.legend() # self.ax.figure.canvas.draw() self.fig.cnvs.update_idletasks() self.fig.cnvs["scrollregion"]=self.fig.cnvs.bbox(ALL)
def plot_day_summary3( ax, closes, ticksize=4, color='k', ): """ Represent the time, open, close, high, low as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. ax : an Axes instance to plot to ticksize : size of open and close ticks in points color : the color of the lines return value is a list of lines added """ rangeSegments = [] pfrom = (0, closes[0]) for i in range(0, len(closes)): if closes[i] >= 0.0: pto = (i, closes[i]) rangeSegments.append((pfrom, pto)) pfrom = pto r, g, b = colorConverter.to_rgb(color) color = r, g, b, 1 useAA = 0, # use tuple here if ticksize > 1: lw = 0.5, # and here else: lw = 0.2, rangeCollection = LineCollection( rangeSegments, colors=color, linewidths=lw, antialiaseds=useAA, ) minx, maxx = (0, len(rangeSegments)) miny = min([low for low in closes if low != -1]) maxy = max([high for high in closes if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) return rangeCollection
def _get_rgb_arrowface(self): """Get the color of the arrow face. """ from matplotlib.cbook import is_string_like from matplotlib.colors import colorConverter facecolor = self._arrowfacecolor if is_string_like(facecolor) and facecolor.lower() == 'none': rgb_face = None else: rgb_face = colorConverter.to_rgb(facecolor) return rgb_face
def make_cmap(colors, position=None, bit=False, webcolors=False): ''' from: http://schubert.atmos.colostate.edu/~cslocum/custom_cmap.html (added support for web colors) make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). make_cmap returns a cmap with equally spaced colors. Arrange your tuples so that the first color is the lowest value for the colorbar and the last is the highest. position contains values from 0 to 1 to dictate the location of each color. ''' import matplotlib as mpl import numpy as np bit_rgb = np.linspace(0,1,256) if position == None: position = np.linspace(0,1,len(colors)) else: if len(position) != len(colors): sys.exit("position length must be the same as colors") elif position[0] != 0 or position[-1] != 1: sys.exit("position must start with 0 and end with 1") ''' if webcolors: bit = False try: for i in range(len(colors)): colors[i] = colorConverter.to_rgb(colors[i]) except ValueError: print("invalid html web color {}.".format(colors[i])) ''' if bit: try: for i in range(len(colors)): colors[i] = (bit_rgb[colors[i][0]], bit_rgb[colors[i][1]], bit_rgb[colors[i][2]]) except: try: for i in range(len(colors)): colors[i] = colorConverter.to_rgb(colors[i]) except ValueError: print("invalid html web color {}.".format(colors[i])) cdict = {'red':[], 'green':[], 'blue':[]} for pos, color in zip(position, colors): cdict['red'].append((pos, color[0], color[0])) cdict['green'].append((pos, color[1], color[1])) cdict['blue'].append((pos, color[2], color[2])) cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256) return cmap
def update_color_physical_network(node_list, colors='b'): global plt_fig, phy_g, virt_g, pos_phy, pos_virt, phy_subplot, virt_subplot, phy_sp_xlim, phy_sp_ylim, \ virt_sp_xlim, virt_sp_ylim, canvas, node_mappings, continue_button, host_color_map phy_subplot = plt_fig.add_subplot(121) plt.axis('off') cl = [] if type(node_list) is not list: nodes = [node_list] else: nodes = node_list if type(colors) is list: for n,c in zip(nodes, colors): host_color_map[n] = colorConverter.to_rgb(c) else: for n in nodes: host_color_map[n] = colorConverter.to_rgb(colors) for node in phy_g.nodes(): cl.append(host_color_map[node]) nx.draw_networkx(phy_g, pos=pos_phy,ax=phy_subplot, with_labels=True, node_color=cl) phy_subplot.set_xlim(phy_sp_xlim) phy_subplot.set_ylim(phy_sp_ylim) plt.axis('off')
def Jmol_color(in_color): if isinstance(in_color, str) and in_color[:2] == "[x" and in_color[-1] == ']': # I guess the user knows what they're doing return in_color #----------------------------------------# if _have_mpl_colors: color = colorConverter.to_rgb(in_color) hex_str = rgb2hex(color) hex_str = "[x" + hex_str[1:] + "]" return hex_str else: # I can't help you, sorry return in_color
def __init__(self, figure): super(ColorCodePatchBuilder, self).__init__(figure, None) self.y_unit = 10**-6 """Unit on the y-axis""" # permission composition shorthands load_store = CheriCapPerm.LOAD | CheriCapPerm.STORE load_exec = CheriCapPerm.LOAD | CheriCapPerm.EXEC store_exec = CheriCapPerm.STORE | CheriCapPerm.EXEC load_store_exec = (CheriCapPerm.STORE | CheriCapPerm.LOAD | CheriCapPerm.EXEC) self._collection_map = { 0: [], CheriCapPerm.LOAD: [], CheriCapPerm.STORE: [], CheriCapPerm.EXEC: [], load_store: [], load_exec: [], store_exec: [], load_store_exec: [], "call": [], } """Map capability permission to the set where the line should go""" self._colors = { 0: colorConverter.to_rgb("#bcbcbc"), CheriCapPerm.LOAD: colorConverter.to_rgb("k"), CheriCapPerm.STORE: colorConverter.to_rgb("y"), CheriCapPerm.EXEC: colorConverter.to_rgb("m"), load_store: colorConverter.to_rgb("c"), load_exec: colorConverter.to_rgb("b"), store_exec: colorConverter.to_rgb("g"), load_store_exec: colorConverter.to_rgb("r"), "call": colorConverter.to_rgb("#31c648"), } """Map capability permission to line colors""" self._patches = None """List of generated patches""" self._node_map = SortedDict() """Maps the Y axis coordinate to the graph node at that position"""
def make_cmap(colors, position=None, bit=False, webcolors=False): ''' from: http://schubert.atmos.colostate.edu/~cslocum/custom_cmap.html (added support for web colors) make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). make_cmap returns a cmap with equally spaced colors. Arrange your tuples so that the first color is the lowest value for the colorbar and the last is the highest. position contains values from 0 to 1 to dictate the location of each color. ''' import matplotlib as mpl import numpy as np bit_rgb = np.linspace(0, 1, 256) if position == None: position = np.linspace(0, 1, len(colors)) else: if len(position) != len(colors): sys.exit("position length must be the same as colors") elif position[0] != 0 or position[-1] != 1: sys.exit("position must start with 0 and end with 1") ''' if webcolors: bit = False try: for i in range(len(colors)): colors[i] = colorConverter.to_rgb(colors[i]) except ValueError: print("invalid html web color {}.".format(colors[i])) ''' if bit: try: for i in range(len(colors)): colors[i] = (bit_rgb[colors[i][0]], bit_rgb[colors[i][1]], bit_rgb[colors[i][2]]) except: try: for i in range(len(colors)): colors[i] = colorConverter.to_rgb(colors[i]) except ValueError: print("invalid html web color {}.".format(colors[i])) cdict = {'red': [], 'green': [], 'blue': []} for pos, color in zip(position, colors): cdict['red'].append((pos, color[0], color[0])) cdict['green'].append((pos, color[1], color[1])) cdict['blue'].append((pos, color[2], color[2])) cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 256) return cmap
def colorAlpha_to_rgb(colors, alpha, bg='w'): """ Given a Matplotlib color and a value of alpha, it returns a RGB color which mimic the RGBA colors on the given background Parameters ---------- colors: Matplotlib color (documentation from matplotlib.colors.colorConverter.to_rgb), list/tuple/numpy array of colors Can be an *RGB* or *RGBA* sequence or a string in any of several forms: 1) a letter from the set 'rgbcmykw' 2) a hex color string, like '#00FFFF' 3) a standard name, like 'aqua' 4) a float, like '0.4', indicating gray on a 0-1 scale if *color* is *RGBA*, the *A* will simply be discarded. alpha: float [0,1] or list/tuple/numpy array with len(colors) elements Value of alpha to mimic. bg: Matplotlib color (optional, default='w') Color of the background. Can be of any type shown in *color* output ------ rgb: *RGB* color example ------- import mimic_alpha as ma print(ma.colorAlpha_to_rgb('r', 0.5)) >>> [array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(['r', 'g'], 0.5)) >>> [array([ 1. , 0.5, 0.5]), array([ 0.5 , 0.75, 0.5 ])] print(ma.colorAlpha_to_rgb(['r', 'g'], [0.5, 0.3])) >>> [array([ 1. , 0.5, 0.5]), array([ 0.7 , 0.85, 0.7 ])] print(ma.colorAlpha_to_rgb(['r', [1,0,0]], 0.5)) >>> [array([ 1. , 0.5, 0.5]), array([ 1. , 0.5, 0.5])] print( ma.colorAlpha_to_rgb([[0,1,1], [1,0,0]], 0.5) ) >>> [array([ 0.5, 1. , 1. ]), array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5)) >>> [array([ 0.5, 1. , 1. ]), array([ 1. , 0.5, 0.5])] print(ma.colorAlpha_to_rgb(np.array([[0,1,1], [1,0,0]]), 0.5, bg='0.5')) >>> [array([ 0.25, 0.75, 0.75]), array([ 0.75, 0.25, 0.25])] """ colors = _to_rgb( colors) #convert the color and save in a list of np arrays bg = np.array(cC.to_rgb(bg)) #convert the background #check if alpha has 1 or len(colors) elements and return a list of len(color) alpha alpha = _check_alpha(alpha, len(colors)) #interpolate between background and color rgb = [(1. - a) * bg + a * c for c, a in zip(colors, alpha)] return rgb
def plot_navpoints(self): for npid in self.navpoints: name, (x, y, z) = self.navpoints[npid] if npid in navpointcolors: color = navpointcolors[npid] else: color = colorConverter.to_rgb('white') s = 7 label = self.navpoints[npid][0].split('.')[1] self.ax.plot([x], [y], [z], markerfacecolor=color, markersize=s, marker='s', label=label)
def ring_color(start_angle, level): from matplotlib.colors import colorConverter # f: [1 - 0.26] # rel: [0 - 198] # icolor: [0 - 5] if level == 1: return colorConverter.to_rgb('#808080') f = 1 - (((level-1) * 0.3) / 8) rel = start_angle / 180. * 99 icolor = int(rel / (100./3)) next_icolor = (icolor + 1) % 6 # Interpolate (?) color = colorConverter.to_rgb(tango_colors[icolor]) next_color = colorConverter.to_rgb(tango_colors[next_icolor]) p = (rel - icolor * 100./3) / (100./3) color = [f * (c - p * (c - n)) for c, n in zip(color, next_color)] return color
def _repr_html_(self): html = '<table style="border: 0;">' for c in self: hx = rgb2hex(colorConverter.to_rgb(c)) html += '<tr style="border: 0;">' '<td style="background-color: {0}; ' 'border: 0;">' '<code style="background-color: {0};">'.format( hx) html += c + '</code></td>' html += '<td style="border: 0"><code>' html += repr(self[c]) + '</code>' html += '</td></tr>' html += '</table>' return html
def plot_axis(self, axis): axis_data = self.evaluate_single_axis(axis) # acquire mutex data mut_speed = axis_data["lock_speedup"] two_std = list(map(lambda x: 2 * sqrt(x), axis_data["lock_var"])) mut_upper_bound = list(map(lambda x, y: x + y, mut_speed, two_std)) mut_lower_bound = list(map(lambda x, y: x - y, mut_speed, two_std)) mut_speed = np.array(mut_speed) mut_upper_bound = np.array(mut_upper_bound) mut_lower_bound = np.array(mut_lower_bound) # acquire local list data list_speed = axis_data["list_speedup"] two_std = list(map(lambda x: 2 * sqrt(x), axis_data["list_var"])) list_upper_bound = list(map(lambda x, y: x + y, list_speed, two_std)) list_lower_bound = list(map(lambda x, y: x - y, list_speed, two_std)) list_speed = np.array(list_speed) list_upper_bound = np.array(list_upper_bound) list_lower_bound = np.array(list_lower_bound) fig = plt.figure(1, figsize=(7, 2.5)) x_axis = np.array(axis_data["x_axis"]) self.plot_mean_and_CI(x_axis, mut_speed, mut_upper_bound, mut_lower_bound, color_mean='k', color_shading='k') self.plot_mean_and_CI(x_axis, list_speed, list_upper_bound, list_lower_bound, color_mean='r--', color_shading='r') bg = np.array([1, 1, 1]) # background of the legend is white colors = ['black', 'red'] # with alpha = .5, the faded color is the average of the background and color colors_faded = [(np.array(cc.to_rgb(color)) + bg) / 2.0 for color in colors] plt.xlabel('threads') plt.ylabel('speed up') plt.legend( [0, 1], ['Lock', 'Local List'], handler_map={ 0: LegendObject(colors[0], colors_faded[0]), 1: LegendObject(colors[1], colors_faded[1], dashed=True), }) plt.title('aggregated speed up') #plt.tight_layout() plt.grid() plt.show()
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]) r, g, b = colorConverter.to_rgb(line.get_color()) color = gtk.gdk.Color(*[int(val * 65535) for val in r, g, b]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) r, g, b = colorConverter.to_rgb(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int(val * 65535) for val in r, g, b]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True
def blend_colors(color, bg, factor): """Blend color with background Parameters ---------- color Color that will be blended. bg Background color. factor : float Blend factor: 0 to 1. """ from matplotlib.colors import colorConverter color, bg = (np.array(colorConverter.to_rgb(c)) for c in (color, bg)) return (1 - factor) * bg + factor * color
def latex_colors(colors, name=''): """ Print a \definecolor command for LaTeX. Parameters ---------- colors: matplotlib color or dict of matplotlib colors A dictionary with names and rgb hex-strings of colors or a single matplotlib color. name: string If colors is a single color, then name is the name of the color. """ if isinstance(colors, dict): for cn in colors: latex_colors(colors[cn], cn) else: r, g, b = cc.to_rgb(colors) print('\\definecolor{%s}{RGB}{%.3f,%.3f,%.3f}' % (name, r, g, b))
def lighter(color, lightness): """Make a color lighter From bendalab/plottools package. Parameters ---------- color: dict or matplotlib color spec A matplotlib color (hex string, name color string, rgb tuple) or a dictionary with an 'color' or 'facecolor' key. lightness: float The smaller the lightness, the lighter the returned color. A lightness of 0 returns white. A lightness of 1 leaves the color untouched. A lightness of 2 returns black. Returns ------- color: string or dict The lighter color as a hexadecimal RGB string (e.g. '#rrggbb'). If `color` is a dictionary, a copy of the dictionary is returned with the value of 'color' or 'facecolor' set to the lighter color. """ try: c = color['color'] cd = dict(**color) cd['color'] = lighter(c, lightness) return cd except (KeyError, TypeError): try: c = color['facecolor'] cd = dict(**color) cd['facecolor'] = lighter(c, lightness) return cd except (KeyError, TypeError): if lightness > 2: lightness = 2 if lightness > 1: return darker(color, 2.0 - lightness) if lightness < 0: lightness = 0 r, g, b = cc.to_rgb(color) rl = r + (1.0 - lightness) * (1.0 - r) gl = g + (1.0 - lightness) * (1.0 - g) bl = b + (1.0 - lightness) * (1.0 - b) return to_hex((rl, gl, bl)).upper()
def darker(color, saturation): """ Make a color darker. From bendalab/plottools package. Parameters ---------- color: dict or matplotlib color spec A matplotlib color (hex string, name color string, rgb tuple) or a dictionary with an 'color' or 'facecolor' key. saturation: float The smaller the saturation, the darker the returned color. A saturation of 0 returns black. A saturation of 1 leaves the color untouched. A saturation of 2 returns white. Returns ------- color: string or dictionary The darker color as a hexadecimal RGB string (e.g. '#rrggbb'). If `color` is a dictionary, a copy of the dictionary is returned with the value of 'color' or 'facecolor' set to the darker color. """ try: c = color['color'] cd = dict(**color) cd['color'] = darker(c, saturation) return cd except (KeyError, TypeError): try: c = color['facecolor'] cd = dict(**color) cd['facecolor'] = darker(c, saturation) return cd except (KeyError, TypeError): if saturation > 2: sauration = 2 if saturation > 1: return lighter(color, 2.0 - saturation) if saturation < 0: saturation = 0 r, g, b = cc.to_rgb(color) rd = r * saturation gd = g * saturation bd = b * saturation return to_hex((rd, gd, bd)).upper()
def get_color_map(color): '''Generate a LinearSegmentedColormap with a single color and varying transparency. Bad values and values below the lower limit are set to be completely transparent. Parameters ---------- color: string or array-like with shape (3,) The color to use when overlaying the survey footprint. Either a string that can be input to colorConverter.to_rgb() or rgb triplet. Returns ------- colormap1: LinearSegmentedColormap A color map that is a single color but varies its opacity from 0.5 to 1. Bad values and values below the minimum are completely transparent. ''' from matplotlib.colors import LinearSegmentedColormap from matplotlib.colors import colorConverter # if the type is a string it is assumed to be an input to allow us # to get an rgb value. If it is not a string and length is 3, it is # assumed to be an actual rgb value if isinstance(color, str): rgb = colorConverter.to_rgb(color) elif len(color) == 3: rgb = color else: raise ValueError('Bad color input') cdict = { 'red': [(0, rgb[0], rgb[0]), (1, rgb[0], rgb[0])], 'green': [(0, rgb[1], rgb[1]), (1, rgb[1], rgb[1])], 'blue': [(0, rgb[2], rgb[2]), (1, rgb[2], rgb[2])], 'alpha': [(0, 0.5, 0.5), (1, 1, 1)] } colormap1 = LinearSegmentedColormap('FootprintCM', cdict) colormap1.set_bad(alpha=0.0) colormap1.set_under(alpha=0.0) return colormap1
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # permission composition shorthands load_store = CheriCapPerm.LOAD | CheriCapPerm.STORE load_exec = CheriCapPerm.LOAD | CheriCapPerm.EXEC store_exec = CheriCapPerm.STORE | CheriCapPerm.EXEC load_store_exec = (CheriCapPerm.STORE | CheriCapPerm.LOAD | CheriCapPerm.EXEC) self._colors = { 0: colorConverter.to_rgb("#bcbcbc"), CheriCapPerm.LOAD: colorConverter.to_rgb("k"), CheriCapPerm.STORE: colorConverter.to_rgb("y"), CheriCapPerm.EXEC: colorConverter.to_rgb("m"), load_store: colorConverter.to_rgb("c"), load_exec: colorConverter.to_rgb("b"), store_exec: colorConverter.to_rgb("g"), load_store_exec: colorConverter.to_rgb("r"), }
def create_plot(self, frame, fig): dkey = list(self.keys())[0] pmap = dataclasses.I3RecoPulseSeriesMap.from_frame(frame, dkey) calib = frame['I3Calibration'] status = frame['I3DetectorStatus'] keys = self.setting('OMKeys') axes = fig.add_subplot(1, 1, 1) # protect against missed clicks keys = [k for k in keys if k in pmap] # FIXME: think of a better way to pick colors and line styles for color, k in colorize(keys): pulses = pmap[k] cal = calib.dom_cal[k] stat = status.dom_status[k] label = 'OM(%d,%d): %.1f PE' % (k.string, k.om, sum(p.charge for p in pulses)) trange = (min(p.time for p in pulses), max(p.time for p in pulses)) wf = dataclasses.I3Waveform() WaveformPlotter.plot_pulses(axes, trange, wf, pulses, cal, stat, color=color, label=label) if ('I3Geometry' in frame): self.addOverlayLine(frame['I3Geometry'].omgeo[k].position, mplcol.to_rgb(color)) axes.set_xlabel('Time [microseconds]', fontsize='smaller') axes.set_ylabel('Toroid output voltage [mV]', fontsize='smaller') if (self.setting('logscale')): axes.set_yscale('log') if (self.setting("Animated")): mintime = min(pulses[0].time for pulses in pmap.values()) - 100 self.timeline = axes.axvline(mintime / 1e3, color='black') if (self.setting('legend')): axes.legend(loc='best', prop={'size': 'small'})
def get_color_arr(c, n, flip_rb=False): """ Convert string c to carr array (N x 3) format """ carr = None; if isinstance(c, str): # single color carr = np.tile(np.array(colorConverter.to_rgb(c)), [n,1]) elif isinstance(c, float): carr = np.tile(np.array(color_func(c)), [n,1]) else: carr = reshape_arr(c) if flip_rb: b, r = carr[:,0], carr[:,2] carr[:,0], carr[:,2] = r.copy(), b.copy() # return floating point with values in [0,1] return carr.astype(np.float32) / 255.0 if carr.dtype == np.uint8 else carr.astype(np.float32)
def headerData(self, section, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: columns = [ 'No.', 'Timestamp', 'Offset', ] + [ 'Head %s' % head.serial for head in self.analyzer.bottle.heads ] return columns[section] elif (orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.ForegroundRole and section >= 3 and matplotlib): return QtGui.QBrush( QtGui.QColor(*(i * 255 for i in colorConverter.to_rgb( matplotlib.rcParams['axes.color_cycle'] [(section - 3) % len(matplotlib.rcParams['axes.color_cycle'])])))) elif orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return section
def _check_color(color): from matplotlib.colors import colorConverter if isinstance(color, str): color = colorConverter.to_rgb(color) elif isinstance(color, collections.abc.Iterable): np_color = np.array(color) if np_color.size % 3 != 0 and np_color.size % 4 != 0: raise ValueError("The expected valid format is RGB or RGBA.") if np_color.dtype == np.int: if (np_color < 0).any() or (np_color > 255).any(): raise ValueError("Values out of range [0, 255].") elif np_color.dtype == np.float: if (np_color < 0.0).any() or (np_color > 1.0).any(): raise ValueError("Values out of range [0.0, 1.0].") else: raise TypeError("Expected data type is `np.int` or `np.float` but " "{} was given.".format(np_color.dtype)) else: raise TypeError("Expected type is `str` or iterable but " "{} was given.".format(type(color))) return color
def _repr_html_(self): html = '<table style="border: 0;">' for c in self: col, i = c.split('_') hx = rgb2hex(colorConverter.to_rgb(col)) if self.map_to_id: self._map_pathname_to_id(c) else: self.c_ids = self[c] html += '<tr style="border: 0;">' \ '<td style="background-color: {0}; ' \ 'border: 0;">' \ '<code style="background-color: {0};">'.format(hx) html += f'Module_{int(i) + 1}' + '</code></td>' html += '<td style="border: 0"><code>' html += ', '.join(self.c_ids) + '</code>' html += '</td></tr>' html += '</table>' return html
def __init__(self, axes): """ Construct the VM-map patch builder. :param axes: the address-space axes where the patches will be rendered :type axes: :class:`matplotlib.axes.Axes` """ super(VMMapPatchBuilder, self).__init__() self.patches = [] """List of rectangles""" self.patch_colors = [] """List of colors for the patches""" self.annotations = [] """Text labels""" self.label_y = 0.5 """ Y position of the label in Axes coordinates (in [0,1])""" self._colors = { "": colorConverter.to_rgb("#bcbcbc"), "r": colorConverter.to_rgb("k"), "w": colorConverter.to_rgb("y"), "x": colorConverter.to_rgb("m"), "rw": colorConverter.to_rgb("c"), "rx": colorConverter.to_rgb("b"), "wx": colorConverter.to_rgb("g"), "rwx": colorConverter.to_rgb("r") } """Map section permission to line colors""" self.transform = transforms.blended_transform_factory( axes.transData, axes.transAxes) """Transform used by the patches"""
def kmeans_plot(X, y, cluster_centers, ax=None): import matplotlib.patheffects as path_effects from sklearn.metrics.pairwise import pairwise_distances_argmin_min if ax is None: ax = plt.gca() # colors = cm.spectral(y.astype(float) / len(cluster_centers)) cmap = cm.get_cmap("Spectral") colors = cmap(y.astype(float) / len(cluster_centers)) ax.scatter(*list(zip(*X)), lw=0, c=colors, s=30) offset = max(list(zip(*cluster_centers))[0]) * 0.2 for i, cluster in enumerate(cluster_centers): index, _ = pairwise_distances_argmin_min(cluster.reshape(1, -1), Y=X) cluster_color = colorConverter.to_rgb(colors[index[0]]) if is_luminous(cluster_color) is False: cluster_color = darken_rgb(cluster_color, 0.35) label = ax.text(x=cluster[0] + offset, y=cluster[1], s='{:d}'.format(i + 1), color=cluster_color) label.set_path_effects([ path_effects.Stroke(lw=2, foreground='white'), path_effects.Normal() ]) limit = max(*ax.get_xlim(), *ax.get_xlim()) ax.set_xlim(0, limit) ax.set_ylim(0, limit) ax.set_xlabel("Feature space for the 1st feature") ax.set_ylabel("Feature space for the 2nd feature") return ax
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = np.asarray(colorConverter.to_rgb(colour)) # 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 discrete_cmap(N=8, colors=None, cmap='viridis', norm=None, use_bounds=False, zero=None): if (colors is None): if (norm is None): if (use_bounds): norm = Normalize(vmin=0, vmax=N - 1) else: norm = Normalize(vmin=-0.5, vmax=N - 0.5) sm = cm.ScalarMappable(cmap=cmap, norm=norm) cols = sm.to_rgba(range(N))[:, :3] else: cols = colors N = len(colors) # Number of rows if (zero is not None): zcol = colorConverter.to_rgb(zero) cols = np.insert(cols, 0, zcol, axis=0) return ListedColormap(cols)
def get_stock_signal_data(): fname = os.path.join(os.getcwd(), 'data', 'stock_data', '_IF000.csv') price_data = csv2frame(fname) from matplotlib.colors import colorConverter info = load_tradeinfo("_djtrend2_IF000") entry_x = [] entry_y = info['entry_price'].tolist() exit_x = [] exit_y = info['exit_price'].tolist() colors = [] for t in info.index: entry_x.append(price_data.index.searchsorted(t)) for t in info['exit_datetime'].values: exit_x.append(price_data.index.searchsorted(t)) for i in range(len(info)): tr = info.ix[i] if tr['islong']: c = 'r' if tr['exit_price']>tr['entry_price'] else 'w' else: c = 'r' if tr['exit_price']<tr['entry_price'] else 'w' r,g,b = colorConverter.to_rgb(c) colors.append((r,g,b,1)) return price_data, entry_x, entry_y, exit_x, exit_y, colors
def mpl_to_plotly_cmap(cmap) -> List: """Convert a matplotlib cmap for use with Plotly. https://plotly.com/python/v3/matplotlib-colorscales/ Args: cmap: The matplotlib colormap Returns: Plotly colorscale """ pl_rgb = [] norm = Normalize(vmin=0, vmax=255) for i in range(0, 255): k = colorConverter.to_rgb(cmap(norm(i))) pl_rgb.append(k) pl_entries = 255 h = 1.0 / (pl_entries - 1) pl_colorscale = [] for k in range(pl_entries): C = list(map(np.uint8, np.array(cmap(k * h)[:3]) * 255)) pl_colorscale.append([k * h, "rgb" + str((C[0], C[1], C[2]))]) return pl_colorscale
def get_stock_signal_data(): from matplotlib.colors import colorConverter signal_data = pd.read_csv('./data/signal_IF000.csv', index_col=0, parse_dates=True) price_data = pd.read_csv('./data/IF000.csv' , index_col=0, parse_dates=True) info = sugar.process_signal(signal_data, price_data) entry_x = [] entry_y = info['entry_price'].tolist() exit_x = [] exit_y = info['exit_price'].tolist() colors = [] for t in info.index: entry_x.append(price_data.index.searchsorted(t)) for t in info['exit_datetime'].values: exit_x.append(price_data.index.searchsorted(t)) for i in range(len(info)): tr = info.ix[i] if tr['islong']: c = 'r' if tr['exit_price']>tr['entry_price'] else 'b' else: c = 'r' if tr['exit_price']<tr['entry_price'] else 'b' r,g,b = colorConverter.to_rgb(c) colors.append((r,g,b,1)) return price_data, entry_x, entry_y, exit_x, exit_y, colors