def cmap_from_color(color, r=0, c='w', alpha=1, name='mycmap', bins=128): """ return cmap object for given color. Cmap is color --> c, d by default is white (1,1,1) parameters: - color : color - r : if r=1 then reverse order - c : second color can be set as tuple (x_r,x_g,x_b) of str ('w', 'k', ...) """ if isinstance(c, str): d = {'w': (1, 1, 1), 'k': (0, 0, 0)} c = d[c] cdict = {} if isinstance(color, str): if '#' in color: color = mcolors.hex2color(color) else: color = mcolors.hex2color(mcolors.cnames[color]) print(color, c) for i, col in enumerate(['red', 'green', 'blue']): if r: cdict[col] = (0.0, color[i], color[i]), (1.0, c[i], c[i]) else: cdict[col] = (0.0, c[i], c[i]), (1.0, color[i], color[i]) plt.register_cmap(name=name, data=cdict, lut=bins) return plt.get_cmap(name)
def ch_color(x, ch=1., alpha=None): """ Modify color applying a multiplier in every channel, or setting an alpha value :param str or iterator x: 3/4 channel normalized color (0->1. * 3/4 ch) or hex color :param float ch: change coefficient :param float alpha: desired alpha value :return: modified color :rtype: tuple """ if type(x) is str: if x.startswith('#'): x = hex2color(x) elif len(x) == 6: x = hex2color('#{}'.format(x)) else: raise ValueError( 'ch_color: Not a valid color for change: {}, type={}'.format( x, type(x))) new_c = [max(0, min(1., ch * c)) for c in x] if alpha is not None: if len(x) == 4: new_c[3] = alpha return tuple(new_c) else: return tuple(new_c + [alpha]) return tuple(new_c)
def __init__(self, index, screen_size=600, spectator=False): self.socket = socketio.Client() self.screenWidth = screen_size self.screenHeight = screen_size self.alive = True self.index = str(index) self.spectator = spectator self.target = {"x": 0, "y": 0} # variables needed for rendering self.cells = [] self.food = {} self.masses = {} self.viruses = {} self.ratio = 1 self.playerMass = 10 self.playerCoords = {"x": 0, "y": 0} self.playerID = "" self.virusFill = list(map(lambda x: int(x * 255), hex2color("#33ff33"))) self.virusStroke = list( map(lambda x: int(x * 255), hex2color("#19D119"))) self.virusStrokeWeight = 4 self.callbacks = {}
def output_graph(coord, centroids, clusters, num_clusters): x_coord = [] y_coord = [] # Divide the coordinates into x and y coordiantes for i in coord: x_coord.append(i[0]) y_coord.append(i[1]) np_x = np.asarray(x_coord) np_y = np.asarray(y_coord) colors_option = [] for i in range(num_clusters): colors_option.append('#'+'%06X' % random.randint(0, 0xFFFFFF)) np_centroids = np.asarray(centroids) while(num_clusters): for i in range(len(coord)): if(clusters[i] == num_clusters-1): plt.scatter(np_x[i],np_y[i],color=colors.hex2color(colors_option[num_clusters-1]),s=6,alpha=0.5) #plot the centroids plt.scatter(np_centroids[num_clusters-1][0],np_centroids[num_clusters-1][1], color=colors.hex2color(colors_option[num_clusters-1]), marker='>', s=150) num_clusters = num_clusters - 1 plt.show()
def _get_node_plot_props(G, node_class=None, max_energy=None, active_node_color=None, active_edge_color=None, dead_node_color=None): """ `node_class` - Generic | Internal | Sensory | Motor `node_size` - proportional to the sum of the presynaptic connections it makes with other nodes. `node_colors` - function of excitatory/inhibitory, energy_value, firing/inactive """ cm = CMAP_DIFF # Shade from red (inhibitory) to green (excitatory) nodes = G.nodes(node_class) adj_matrix = nx.adjacency_matrix(G) node_pos = nx.get_node_attributes(G.subgraph(nodes), 'pos') edge_width = np.array([d['weight'] for (u, v, d) in G.edges(data=True) if u in nodes]) firing_nc = colors.hex2color(active_node_color) if active_node_color is not None \ else list(colors.hex2color(RENDER_NODE_PROPS['Firing']['node_face_color'])) dead_nc = colors.hex2color(dead_node_color) if dead_node_color is not None \ else list(colors.hex2color(RENDER_NODE_PROPS['Dead']['node_face_color'])) _ = firing_nc.append(1.) _ = dead_nc.append(1.) node_colors = _get_node_colors(G, cm, node_class=node_class, max_energy=max_energy, firing_node_color=firing_nc, dead_node_color=dead_nc) if node_class is not None: min_ns, max_ns = RENDER_NODE_PROPS[node_class]['min_node_size'], RENDER_NODE_PROPS[node_class]['max_node_size'] node_shape = RENDER_NODE_PROPS[node_class]['shape'] node_size = np.array([np.maximum(adj_matrix[i].sum(), .01) for i, n_id in enumerate(G.nodes()) if G.node[n_id]['node_class'] == node_class]) # proportional to the number of connections else: node_shape, node_size = RENDER_NODE_PROPS['Default']['shape'], adj_matrix.sum(axis=1) min_ns, max_ns = RENDER_NODE_PROPS['Default']['min_node_size'], RENDER_NODE_PROPS['Default']['max_node_size'] node_size = min_ns + (max_ns - min_ns) * (node_size - node_size.min()) / (node_size.max() - node_size.min()) \ if node_size.max() > node_size.min() else max_ns * np.ones_like(node_size) return node_pos, node_colors, node_shape, node_size, edge_width
def interpolatecolour(locolour, hicolour, value): acolour = 0.0, 0.0, 0.0 zcolour = 1.0, 1.0, 1.0 if type(locolour) == str and locolour.startswith("#"): acolour = cols.hex2color(locolour) elif type(locolour) == list and all(isinstance(x, float) for x in locolour): acolour = locolour[0], locolour[1], locolour[2] elif type(locolour) == np.ndarray and locolour.dtype == np.float64: acolour = float(locolour[0]), float(locolour[1]), float(locolour[2]) else: raise ValueError( "Couldn't make sense of locolour value, needs to be hexadecimal notation with '#', or list of floats, or numpy ndarray." ) if type(hicolour) == str and hicolour.startswith("#"): zcolour = cols.hex2color(hicolour) elif type(hicolour) == list and all(isinstance(x, float) for x in locolour): zcolour = hicolour[0], hicolour[1], hicolour[2] elif type(hicolour) == np.ndarray and hicolour.dtype == np.float64: zcolour = float(hicolour[0]), float(hicolour[1]), float(hicolour[2]) else: raise ValueError( "Couldn't make sense of hicolour value, needs to be hexadecimal notation with '#', or list of floats, or numpy ndarray." ) return ( value * (zcolour[0] - acolour[0]) + acolour[0], value * (zcolour[1] - acolour[1]) + acolour[1], value * (zcolour[2] - acolour[2]) + acolour[2], )
def get_color_as_rgba_f(color): color_dev = get_color_dev(color) a = 1. if color_dev == 'name': hex_color = COLORS[color] rgbf = mpl_colors.hex2color(hex_color) elif color_dev == 'hex': rgbf = mpl_colors.hex2color(color[:7]) if len(color) > 7: a = int(color[-2:], 16) / 255. elif color_dev == 'rgb': rgbf = parse_color_to_mpl_color(color) elif color_dev == 'rgba': rgbaf = parse_color_to_mpl_color(color) a = rgbaf[-1] rgbf = rgbaf[:3] elif color_dev == 'rgbF': rgbf = parse_color_to_mpl_color(color) elif color_dev == 'rgbaF': rgbaf = parse_color_to_mpl_color(color) rgbf = rgbaf[:3] a = rgbaf[-1] else: return None rgbaf = tuple(list(rgbf) + [a]) return rgbaf
def ch_color(x, ch=1., alpha=None): """ Modify color applying a multiplier in every channel, or setting an alpha value :param str or iterator x: 3/4 channel normalized color (0->1. * 3/4 ch) or hex color :param float ch: change coefficient :param float alpha: desired alpha value :return: modified color :rtype: tuple """ if type(x) is str: if x.startswith('#'): x = hex2color(x) elif len(x) == 6: x = hex2color('#{}'.format(x)) else: raise ValueError('ch_color: Not a valid color for change: {}, type={}'.format(x, type(x))) new_c = [max(0, min(1., ch * c)) for c in x] if alpha is not None: if len(x) == 4: new_c[3] = alpha return tuple(new_c) else: return tuple(new_c + [alpha]) return tuple(new_c)
def __color_map(opinion): if opinion == 0: # red return mc.hex2color("#f3722c") + (1,) if opinion == 1: # green return mc.hex2color("#43aa8b") + (1,)
def hex3colormap(hex1, hex2, hex3): from matplotlib.colors import hex2color from matplotlib.colors import LinearSegmentedColormap some_name = 'some_name' [hex1r, hex1g, hex1b] = hex2color(hex1) [hex2r, hex2g, hex2b] = hex2color(hex2) [hex3r, hex3g, hex3b] = hex2color(hex3) cdict = {'red': ((0.0, hex1r, hex1r), (0.5, hex2r, hex2r), (1.0, hex3r, hex3r)), 'green': ((0.0, hex1g, hex1g), (0.5, hex2r, hex2r), (1.0, hex3g, hex3g)), 'blue': ((0.0, hex1b, hex1b), (0.5, hex2r, hex2r), (1.0, hex3b, hex3b)) } colormapname2 = LinearSegmentedColormap(some_name, cdict) return colormapname2
def add_pie_chart(summary_counts, sample_name, fig, graph_i, graphs_num): """ Add a pie chart to a Wild Life of Our Homes data visualization figure. """ ax = fig.add_axes([0.25, 0.02 + (0.98 / graphs_num) * graph_i, 0.50, (0.98 / graphs_num)]) ax.set_aspect(1) color_set = [c for c in colors.cnames if sum(colors.hex2color(colors.cnames[c])) < 2.5 and sum(colors.hex2color(colors.cnames[c])) > 1] random.shuffle(color_set) color_set = color_set[0:len(summary_counts)] pie_chart = ax.pie( [sc[1] for sc in summary_counts], labels=['/'.join(sc[0]) for sc in summary_counts], labeldistance=1.05, pctdistance=0.67, colors=color_set, autopct='%1.1f%%') center_circle = plt.Circle((0, 0), 0.75, color='white', fc='white') fig = plt.gcf() fig.gca().add_artist(center_circle) for pie_wedge in pie_chart[0]: pie_wedge.set_edgecolor('white') for t in pie_chart[1]: t.set_size('smaller') for t in pie_chart[2]: t.set_size('x-small') ax.set_title(sample_name) ax.text(-0.6, -1.35, 'Groups with less than 0.4% not depicted.')
def hot_overflow(underflowcol='magenta', overflowcol='lime', percentage=5): if percentage < 1: percentage = 1 if percentage > 15: percentage = 15 ucolrgb = mcol.hex2color(mcol.cnames[underflowcol]) ocolrgb = mcol.hex2color(mcol.cnames[overflowcol]) p = 0.01 * percentage # edited from hot_data in matplotlib hot_data = { 'red': [(0, r(ucolrgb), r(ucolrgb)), (p, r(ucolrgb), 0.0416), (0.365079, 1.000000, 1.000000), (1.0 - p, 1.0, r(ocolrgb)), (1.0, r(ocolrgb), r(ocolrgb))], 'green': [(0, g(ucolrgb), g(ucolrgb)), (p, g(ucolrgb), 0.), (0.365079, 0.000000, 0.000000), (0.746032, 1.000000, 1.000000), (1.0 - p, 1.0, g(ocolrgb)), (1.0, g(ocolrgb), g(ocolrgb))], 'blue': [(0, b(ucolrgb), b(ucolrgb)), (p, b(ucolrgb), 0.), (0.746032, 0.000000, 0.000000), (1.0 - p, 1.0, b(ocolrgb)), (1.0, b(ocolrgb), b(ocolrgb))] } cm_hot2 = mcol.LinearSegmentedColormap('hot_overflow', hot_data) return cm_hot2
def get_colors(n, first='#1f77b4', last='#d62728'): """Return a list of colors interpolating between the first and last. The function accepts both strings representing hex colors and tuples containing RGB values, which must be between 0 and 1. Parameters ---------- n : int Number of colors to be generated. first : str or tuple of float First color in the list (defaults to Matplotlib default blue). last : str, tuple Last color in the list(defaults to Matplotlib default red). Returns ------- colors : list A list of strings containing hex colors """ if not isinstance(first, tuple): first = hex2color(first) if not isinstance(last, tuple): last = hex2color(last) return [rgb2hex((first[0]+(last[0]-first[0])*i/(n-1), first[1]+(last[1]-first[1])*i/(n-1), first[2]+(last[2]-first[2])*i/(n-1))) for i in range(n)]
def get_colors(n, first='#1f77b4', last='#d62728'): """Return a list of colors interpolating between the first and last. The function accepts both strings representing hex colors and tuples containing RGB values, which must be between 0 and 1. Parameters ---------- n : int Number of colors to be generated. first : str or tuple of float First color in the list (defaults to Matplotlib default blue). last : str, tuple Last color in the list(defaults to Matplotlib default red). Returns ------- colors : list A list of strings containing hex colors """ if not isinstance(first, tuple): first = hex2color(first) if not isinstance(last, tuple): last = hex2color(last) return [ rgb2hex((first[0] + (last[0] - first[0]) * i / (n - 1), first[1] + (last[1] - first[1]) * i / (n - 1), first[2] + (last[2] - first[2]) * i / (n - 1))) for i in range(n) ]
def setup_plot(self): gs = GridSpec(1, 2, width_ratios=[9.5, 0.5]) self.axes = self.figure.add_subplot(gs[0], projection='3d') numformatter = ScalarFormatter(useOffset=False) timeFormatter = DateFormatter("%H:%M:%S") self.axes.set_xlabel("Frequency (MHz)") self.axes.set_ylabel('Time') self.axes.set_zlabel('Level (dB)') self.axes.w_xaxis.set_pane_color(hex2color(self.settings.background)) self.axes.w_yaxis.set_pane_color(hex2color(self.settings.background)) self.axes.w_zaxis.set_pane_color(hex2color(self.settings.background)) self.axes.xaxis.set_major_formatter(numformatter) self.axes.yaxis.set_major_formatter(timeFormatter) self.axes.zaxis.set_major_formatter(numformatter) self.axes.xaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.zaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.set_xlim(self.settings.start, self.settings.stop) now = time.time() self.axes.set_ylim(epoch_to_mpl(now), epoch_to_mpl(now - 10)) self.axes.set_zlim(-50, 0) self.bar = self.figure.add_subplot(gs[1]) norm = Normalize(vmin=-50, vmax=0) self.barBase = ColorbarBase(self.bar, norm=norm, cmap=cm.get_cmap(self.settings.colourMap)) self.barBase.set_label('Level (dB)')
def grey_overflow(underflowcol = 'magenta', overflowcol = 'lime', percentage=5, greystart=0.1): if percentage < 1: percentage = 1 if percentage > 15: percentage = 15 ucolrgb = colors.hex2color(colors.cnames[underflowcol]) ocolrgb = colors.hex2color(colors.cnames[overflowcol]) p = 0.01 * percentage def r(rgb): return rgb[0] def g(rgb): return rgb[1] def b(rgb): return rgb[2] grey_data = {'red': [(0, r(ucolrgb), r(ucolrgb)), (p, r(ucolrgb), greystart), (1.0-p, 1.0, r(ocolrgb)), (1.0, r(ocolrgb), r(ocolrgb))], 'green': [(0, g(ucolrgb), g(ucolrgb)), (p, g(ucolrgb), greystart), (1.0-p, 1.0, g(ocolrgb)), (1.0, g(ocolrgb), g(ocolrgb))], 'blue': [(0, b(ucolrgb), b(ucolrgb)), (p, b(ucolrgb), greystart), (1.0-p, 1.0, b(ocolrgb)), (1.0, b(ocolrgb), b(ocolrgb))]} cm_grey2 = colors.LinearSegmentedColormap('grey_overflow', grey_data) return cm_grey2
def drawCar(car): myCoordinates=car.coordinates x_coor=myCoordinates.x y_coor=myCoordinates.y y_coor = y_coor*ROAD_SECTION_HEIGHT x_coor = x_coor*ROAD_SECTION_WIDTH enable_stroke() set_stroke_width(2) if (car.wantsToPark): color = colors.hex2color(Theme.Car_Parking) set_fill_color(color[0],color[1],color[2]) set_stroke_color(color[0],color[1],color[2]) else: color = colors.hex2color(Theme.Car_Done) set_fill_color(color[0],color[1],color[2]) set_stroke_color(color[0],color[1],color[2]) if(car.direction == Direction.North): x_coor = x_coor+(ROAD_SECTION_WIDTH/2)+(ROAD_SECTION_WIDTH/5) y_coor = y_coor + (ROAD_SECTION_HEIGHT/2) elif(car.direction == Direction.South): x_coor = x_coor+(ROAD_SECTION_WIDTH/2)-(ROAD_SECTION_WIDTH/5) y_coor = y_coor + (ROAD_SECTION_HEIGHT/2) elif(car.direction == Direction.West): y_coor = y_coor+(ROAD_SECTION_HEIGHT/2)+(ROAD_SECTION_HEIGHT/5) x_coor = x_coor + (ROAD_SECTION_WIDTH/2) elif(car.direction == Direction.East): y_coor = y_coor+(ROAD_SECTION_HEIGHT/2)-(ROAD_SECTION_HEIGHT/5) x_coor = x_coor + (ROAD_SECTION_WIDTH/2) draw_circle(x_coor,y_coor,ROAD_SECTION_WIDTH/4) disable_stroke()
def get_lut(ncol=20, lut_type='mat', maxind=20, vrange=(0, 1)): if lut_type == 'mat': c = [ '#ffdcd2', '#ffa4a4', '#f98568', '#da180e', '#ffffc6', '#def538', '#b0b000', '#878e2b', '#dbfdc6', '#8bf391', '#5ac960', '#658750', '#e0e4fe', '#bb9af1', '#548bcf', '#fdcbfe', '#e75ae3', '#ad5ab4', '#abe3e7', '#67b1ae' ] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(ncol * int(np.ceil(maxind / 20.))) for k in range(ncol * int(np.ceil(maxind / 20.))): cv = colors.hex2color(c[k % 20]) lut.SetTableValue(k, cv[0], cv[1], cv[2]) elif lut_type == 'maps': c = [ '#4b0bf4', '#3c8aff', '#3da7fe', '#3fbefc', '#45d7f5', '#53e8e8', '#5fdcc2', '#58e28f', '#51ee4d', '#8ffb40', '#bbfb75', '#d8fe63', '#ffff00', '#f1e723', '#efd850', '#eeba4d', '#f28b40', '#fe4743', '#e90601', '#c15004' ] lut = vtk.vtkDiscretizableColorTransferFunction() lut.DiscretizeOn() lut.SetNumberOfValues(ncol) dv = vrange[1] - vrange[0] for k, cc in enumerate(c): cv = colors.hex2color(cc) lut.AddRGBPoint(k * dv / ncol + vrange[0], cv[0], cv[1], cv[2]) return lut
def convertToRGB(dict, color, fgcol): #jesli color byl juz zapisany w rgb if color[0] == "(" and color[len(color) - 1] == ")": color = color.strip('(') color = color.strip(')') color = color.split(',') return tuple([(int(c)) for c in color]) #jesli kolor byl zapisany w notacji html if color[0] == "#": #color = color.strip('#') hex = colors.hex2color(color) return tuple([int(255 * c) for c in hex]) #jesli kolor byl w postaci slownej palette = dict['Palette'] for col in palette: if col == color: hex = colors.hex2color(color) return tuple([int(255 * c) for c in hex]) print("Danego koloru nie ma w podanej gamie kolorow: " + color) return fgcol
def color2vb(color=None, default=(1., 1., 1.), length=1, alpha=1.0): """Turn into a RGBA compatible color format. This function can tranform a tuple of RGB, a matplotlib color or an hexadecimal color into an array of RGBA colors. Parameters ---------- color : None/tuple/string | None The color to use. Can either be None, or a tuple (R, G, B), a matplotlib color or an hexadecimal color '#...'. default : tuple | (1,1,1) The default color to use instead. length : int | 1 The length of the output array. alpha : float | 1 The opacity (Last digit of the RGBA tuple). Return ------ vcolor : array_like Array of RGBA colors of shape (length, 4). """ # Default or static color : if (color is None) or isinstance(color, (str, tuple, list, np.ndarray)): if color is None: # Default coltuple = default elif isinstance(color, (tuple, list, np.ndarray)): # Static color = np.squeeze(color).ravel() if len(color) == 4: alpha = color[-1] color = color[0:-1] coltuple = color elif isinstance(color, str) and (color[0] is not '#'): # Matplotlib # Check if the name is in the Matplotlib database : if color in mplcol.cnames.keys(): coltuple = mplcol.hex2color(mplcol.cnames[color]) else: warn("The color name " + color + " is not in the matplotlib " "database. Default color will be used instead.") coltuple = default elif isinstance(color, str) and (color[0] is '#'): # Hexadecimal try: coltuple = mplcol.hex2color(color) except: warn("The hexadecimal color " + color + " is not valid. " "Default color will be used instead.") coltuple = default # Set the color : vcolor = np.concatenate( (np.array([list(coltuple)] * length), alpha * np.ones( (length, 1), dtype=np.float32)), axis=1) return vcolor.astype(np.float32) else: raise ValueError( str(type(color)) + " is not a recognized type of " "color. Use None, tuple or string")
def hex_to_rgb(self, hex_str): rgb_color = hex2color(hex_str) upscaled_rgb = [i * 255 for i in rgb_color] # print("hex:", hex_str) rgb_color = hex2color(hex_str) upscaled_rgb = [i * 255 for i in rgb_color] # print("upscaled rgb:", upscaled_rgb) return upscaled_rgb
def get_edge_color(row): source_rgb = np.asarray(hex2color(node_color_dict[row['source']])) target_rgb = np.asarray(hex2color(node_color_dict[row['target']])) rgb = 0.5 * (source_rgb + target_rgb) return rgb2hex(rgb)
def get_line_color(ix, modifier=None): colour = _lines_colour_cycle[ix] if modifier == 'dark': return tuple(c / 2 for c in colors.hex2color(colour)) elif modifier == 'light': return tuple(1 - (1 - c) / 2 for c in colors.hex2color(colour)) elif modifier is not None: raise NotImplementedError(modifier) return colors.hex2color(colour)
def get_line_color(ix, modifier=None): colour = _lines_colour_cycle[ix] if modifier=='dark': return tuple(c/2 for c in colors.hex2color(colour)) elif modifier=='light': return tuple(1-(1-c)/2 for c in colors.hex2color(colour)) elif modifier is not None: raise NotImplementedError(modifier) return colors.hex2color(colour)
def test_get_random_color(self): ''' Should return HEX code of random color ''' c0 = get_random_color() c1 = get_random_color(c0) c2 = get_random_color(c1, 300) self.assertEqual(type(hex2color(c0)), tuple) self.assertEqual(type(hex2color(c1)), tuple) self.assertEqual(type(hex2color(c2)), tuple)
def mt_plot(): """ Return a moment tensor image. """ formats = { "png": "image/png", "svg": "image/svg+xml" } args = flask.request.args m_rr = float(args["m_rr"]) m_tt = float(args["m_tt"]) m_pp = float(args["m_pp"]) m_rt = float(args["m_rt"]) m_rp = float(args["m_rp"]) m_tp = float(args["m_tp"]) focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) # Allow hexcolors. color = args.get("color", "red") try: hexcolor = "#" + color hex2color(hexcolor) color = hexcolor except ValueError: pass size = int(args.get("size", 32)) lw = float(args.get("lw", 1)) format = args.get("format", "png") if format not in formats.keys(): flask.abort(500) dpi = 100 fig = plt.figure(figsize=(float(size) / float(dpi), float(size) / float(dpi)), dpi=dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) bb = Beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color) ax.add_collection(bb) ax.set_xlim(-105, 105) ax.set_ylim(-105, 105) temp = io.BytesIO() plt.savefig(temp, format=format, dpi=dpi, transparent=True) plt.close(fig) plt.close("all") temp.seek(0, 0) return flask.send_file(temp, mimetype=formats[format], add_etags=False, attachment_filename="mt.%s" % format)
def __init__(self, pdb_object, structure_name, residues_of_interest = [], label_all_residues_of_interest = False, **kwargs): '''The chain_seed_color kwarg can be either: - a triple of R,G,B values e.g. [0.5, 1.0, 0.75] where each value is between 0.0 and 1.0; - a hex string #RRGGBB e.g. #77ffaa; - a name defined in the predefined dict above e.g. "aquamarine". ''' self.pdb_object = pdb_object self.structure_name = structure_name self.add_residues_of_interest(residues_of_interest) self.label_all_residues_of_interest = label_all_residues_of_interest self.chain_colors = kwargs.get('chain_colors') or {} # Set up per-chain colors try: if not self.chain_colors and kwargs.get('chain_seed_color'): chain_seed_color = kwargs.get('chain_seed_color') if isinstance(chain_seed_color, str) or isinstance(chain_seed_color, unicode): chain_seed_color = str(chain_seed_color) if chain_seed_color.startswith('#'): if len(chain_seed_color) != 7: chain_seed_color = None else: trpl = predefined.get(chain_seed_color) chain_seed_color = None if trpl: chain_seed_color = mpl_colors.rgb2hex(trpl) elif isinstance(chain_seed_color, list) and len(chain_seed_color) == 3: chain_seed_color = mpl_colors.rgb2hex(chain_seed_color) if chain_seed_color.startswith('#') and len(chain_seed_color) == 7: # todo: We are moving between color spaces multiple times so are probably introducing artifacts due to rounding. Rewrite this to minimize this movement. chain_seed_color = chain_seed_color[1:] hsl_color = colorsys.rgb_to_hls(int(chain_seed_color[0:2], 16)/255.0, int(chain_seed_color[2:4], 16)/255.0, int(chain_seed_color[4:6], 16)/255.0) chain_seed_hue = int(360.0 * hsl_color[0]) chain_seed_saturation = max(0.15, hsl_color[1]) # otherwise some colors e.g. near-black will not yield any alternate colors chain_seed_lightness = max(0.15, hsl_color[2]) # otherwise some colors e.g. near-black will not yield any alternate colors min_colors_in_wheel = 4 # choose at least 4 colors - this usually results in a wider variety of colors and prevents clashes e.g. given 2 chains in both mut and wt, wt seeded with blue, and mut seeded with yellow, we will get a clash chain_ids = sorted(pdb_object.atom_sequences.keys()) # Choose complementary colors, respecting the original saturation and lightness values chain_colors = ggplot_color_wheel(max(len(chain_ids), min_colors_in_wheel), start = chain_seed_hue, saturation_adjustment = None, saturation = chain_seed_saturation, lightness = chain_seed_lightness) assert(len(chain_colors) >= len(chain_ids)) self.chain_colors = {} for i in xrange(len(chain_ids)): self.chain_colors[chain_ids[i]] = str(list(mpl_colors.hex2color('#' + chain_colors[i]))) # Force use of the original seed as this may have been altered above in the "= max(" statements self.chain_colors[chain_ids[0]] = str(list(mpl_colors.hex2color('#' + chain_seed_color))) except Exception, e: print('An exception occurred setting the chain colors. Ignoring exception and resuming with default colors.') print(str(e)) print(traceback.format_exc())
def main(): allX = [] allY = [] centroidsX = [] centroidsY = [] cluster = [] oldCluster = [] colorArray = [] stop = False maxIteration = 100 iterations = 0 numOfClusters = int(sys.argv[1]) filename = str(sys.argv[2]) allX, allY = readFile(filename) maxX = max(allX) maxY = max(allY) minX = min(allX) minY = min(allY) # initials centroids centroidsX, centroidsY = findRandomCentroids(numOfClusters, minX, maxX, minY, maxY) # labels each point with appropriate centroid cluster = assignCentroids(allX, allY, centroidsX, centroidsY) # continuously looking for new cluster and new centroids until convergence while (stop == False): oldCluster = cluster centroidsX, centroidsY = findCentroids(numOfClusters, cluster, allX, allY) cluster = assignCentroids(allX, allY, centroidsX, centroidsY) iterations += 1 if ((oldCluster == cluster) or (iterations == maxIteration)): stop = True x = np.asarray(allX) y = np.asarray(allY) centX = np.asarray(centroidsX) centY = np.asarray(centroidsY) for i in range(numOfClusters): colorArray.append('#'+'%06X' % random.randint(0, 0xFFFFFF)) #plt.scatter(x, y,color=colors.hex2color(colorArray[0]), s=1, alpha=0.5) for j in range(len(centX)): plt.scatter(centX[j], centY[j], color = colors.hex2color(colorArray[j])) for i in range(len(cluster)): if (cluster[i] == j): plt.scatter(x[i], y[i], color=colors.hex2color(colorArray[j]), s=5, alpha=0.5) plt.show()
def runGraphics(): color = colors.hex2color(Color.White) set_clear_color(color[0],color[1],color[2]) clear() #Grass disable_stroke() color = colors.hex2color(Theme.Background) set_fill_color(color[0],color[1],color[2]) draw_rectangle(0,0,CANVAS_WIDTH,CANVAS_HEIGHT) while not window_closed(): numDriving = len([car for car in carList if car.parkingSpot == None]) for i in range(numDriving): env.step() if numDriving == 0: env.step() for road in cityMap.roads: for roadSection in road.roadSections: drawRoadSection(roadSection) for car in carList: drawCar(car) request_redraw() sleep(STEP_LENGTH) if is_key_pressed("p"): while 1: if is_key_pressed("r"): break; sleep(0.1) update_progress(float(len([car for car in carList if len(car.destinations) == 0]))/float(len(carList))) if float(len([car for car in carList if len(car.destinations) == 0]))/float(len(carList)) > .97: sys.stdout.write("\n") print("Finished Simulation!") break fp=open(logname,"w") fp.write("Parking Log\n") total=0 totalAverage = 0 totalDistanceAverage = 0 for car in carList: averageTime = (car.timeSpent / car.totalDestinations) averageDistance = (car.distanceFrom / car.totalDestinations) totalAverage += averageTime totalDistanceAverage += averageDistance total += car.timeSpent fp.write("Car: "+str(car.getCarID())+" Total Time Spent Searching: "+str(car.timeSpent)+ " Average Time Spent Searching: " + str(averageTime) + "For an average distance from destination of: " + str(averageDistance) + "\n") fp.write("Total Time Spent Looking for Parking by All Cars: "+str(total)+ " Average Time Spent Looking: " + str(totalAverage/len(carList)) + " Average Distance from destination: " + str(totalDistanceAverage/len(carList))+"\n") fp.close() sys.exit(0)
def plot_regions(projection, regions_filepath, regions_dirpath, title, lat_range=ALL_LAT_RANGE, long_range=ALL_LONG_RANGE): """ Returns ------- fig, ax """ fig, ax = plt.subplots() ax.set_title(title) # get region economic prosperity levels econ_levels = [] with open(regions_filepath) as file: for line in file: _, econ_level = line.strip().split("|") econ_levels.append(int(econ_level)) # setup coloring ax.set_axis_bgcolor("#BFECFF") # ocean blue # color map econ_cmap = colors.LinearSegmentedColormap.from_list( 'econ_colors', [colors.hex2color("#DDFF28"), colors.hex2color("#D70A0A")]) sm = plt.cm.ScalarMappable(cmap=econ_cmap, norm=plt.Normalize(vmin=1, vmax=7)) # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = fig.colorbar(sm, ticks=[7, 6, 5, 4, 3, 2, 1]) cbar.set_label("Economic level", rotation=270) cbar.ax.get_yaxis().labelpad = 15 # optimization norm = 1/ECONOMIC_LEVELS # walk through regions directory and plot all the regions _, regions_dirs, _ = next(os.walk(regions_dirpath)) regions_dirs = [d for d in regions_dirs if d[0] != "."] # remove hidden subdirectories for reg_dir in regions_dirs: root, _, files = next(os.walk(os.path.join(regions_dirpath, reg_dir))) files = [f for f in files if f[0] != "."] # remove hidden files for file in files: if file.startswith("landshape"): landshape_coords = get_landshape_coords(os.path.join(root, file)) elif file.startswith("landparts"): landparts = get_landparts(os.path.join(root, file)) if lat_range != ALL_LAT_RANGE or long_range != ALL_LONG_RANGE: landshape_coords, landparts = filter_landshape_landparts( landshape_coords, landparts, lat_range, long_range) # if everything was filtered out, continue to next region if len(landshape_coords) <= 2: continue color = econ_cmap(econ_levels[int(reg_dir)] * norm) color = colors.rgb2hex(color) plot_landparts(ax, projection, landshape_coords, landparts, color) fig.tight_layout() return fig, ax
def mt_plot(): """ Return a moment tensor image. """ formats = {"png": "image/png", "svg": "image/svg+xml"} args = flask.request.args m_rr = float(args["m_rr"]) m_tt = float(args["m_tt"]) m_pp = float(args["m_pp"]) m_rt = float(args["m_rt"]) m_rp = float(args["m_rp"]) m_tp = float(args["m_tp"]) focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) # Allow hexcolors. color = args.get("color", "red") try: hexcolor = "#" + color hex2color(hexcolor) color = hexcolor except ValueError: pass size = int(args.get("size", 32)) lw = float(args.get("lw", 1)) format = args.get("format", "png") if format not in formats.keys(): flask.abort(500) dpi = 100 fig = plt.figure(figsize=(float(size) / float(dpi), float(size) / float(dpi)), dpi=dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) bb = beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color) ax.add_collection(bb) ax.set_xlim(-105, 105) ax.set_ylim(-105, 105) temp = io.BytesIO() plt.savefig(temp, format=format, dpi=dpi, transparent=True) plt.close(fig) plt.close("all") temp.seek(0, 0) return flask.send_file(temp, mimetype=formats[format], add_etags=False, attachment_filename="mt.%s" % format)
def format_progress(hexcolor0, hexcolor1, formstring, entry_current_page, entry_length): ratio = 1.0 * int(entry_current_page) / int(entry_length) # Do stuff with color diff color0 = colors.hex2color(hexcolor0) color1 = colors.hex2color(hexcolor1) color_red = ratio * (color1[0] - color0[0]) + color0[0] color_green = ratio * (color1[1] - color0[1]) + color0[1] color_blue = ratio * (color1[2] - color0[2]) + color0[2] color_str = colors.rgb2hex((color_red, color_green, color_blue)) return progresstemplate_row.format(progresscolor=color_str, current_page = int(entry_current_page), length=int(entry_length))
def draw_networkx(G, pos=None, ax=None, max_e=None, plot_active=True, active_node_color=None, **kwargs): internal_color, internal_ecolor, internal_alpha = '#FCDC79', '#C79500', 0.5 overall_color, overall_ecolor, overall_alpha = '#A1A1A1', '#050505', 0.2 if ax is None: fig, ax = plt.subplots() for node_class in RENDER_NODE_PROPS.iterkeys(): if node_class in ['Default', 'Active', 'Dead', 'Firing']: continue gs = G.subgraph(G.nodes(node_class)).copy() node_pos, node_colors, node_shape, node_size, edge_width = _get_node_plot_props(gs, node_class, max_energy=max_e) nx.draw_networkx_nodes(gs, node_pos, node_color=node_colors, node_shape=node_shape, node_size=node_size, ax=ax, **kwargs) node_pos, node_colors, node_shape, node_size, edge_width = _get_node_plot_props(G, max_energy=max_e) if pos is not None: node_pos = pos nx.draw_networkx_edges(G, node_pos, width=edge_width, alpha=0.2, ax=ax) # draw edges i_subg = G.subgraph(G.nodes('Internal')) m_subg = G.subgraph(G.nodes('Motor')) s_subg = G.subgraph(G.nodes('Sensory')) # Add patches for the entire network and internal nodes ax.add_patch( create_axes_patch(nx.get_node_attributes(G, 'pos').values(), scale=1.2, facecolor=overall_color, edgecolor=overall_ecolor, alpha=overall_alpha)) ax.add_patch( create_axes_patch(nx.get_node_attributes(i_subg, 'pos').values(), scale=1.2, facecolor=internal_color, edgecolor=internal_ecolor, alpha=internal_alpha)) # Add arrows indicating force direction firing_nc = colors.hex2color(active_node_color) if active_node_color is not None \ else list(colors.hex2color(RENDER_NODE_PROPS['Firing']['node_face_color'])) arrow_scale = 1 for m_id, attr in m_subg.node.iteritems(): arr_cl = firing_nc if G.is_node_firing(m_id) else 'k' if len(attr['force_direction']) == 1: dx, dy = attr['force_direction'][0], 0. else: dx, dy = attr['force_direction'] ax.arrow(attr['pos'][0], attr['pos'][1], dx * arrow_scale, dy * arrow_scale, head_width=1, head_length=np.linalg.norm(attr['force_direction'])/2, fc='k', ec=arr_cl) labels = nx.draw_networkx_labels(G, pos=node_pos, font_color='w') xlim, ylim = ax.get_xlim(), ax.get_ylim() ax.set_xlim([xlim[0]-arrow_scale, xlim[1]+arrow_scale]) ax.set_ylim([ylim[0] - arrow_scale, ylim[1] + arrow_scale]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # ax.set_title("%s Network @ t:%d" %("ID", 0), {'fontsize': 10}) ax.set_aspect('equal') ax.set(**kwargs) return ax
def color_difference(coll1, coll2): # First color col1 = hex2color(coll1) color1_rgb = sRGBColor(col1[0], col1[1], col1[2]) # Second color col2 = hex2color(coll2) color2_rgb = sRGBColor(col2[0], col2[1], col2[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) # Convert from RGB to Lab Color Space color2_lab = convert_color(color2_rgb, LabColor) # Find the color difference delta_e = delta_e_cie2000(color1_lab, color2_lab) #print "The difference between the 2 color = ", delta_e return delta_e
def pm_array_graphics(cell_points_outers_inners, axes=None): # Create and return graphical elements for the PM, from given path points. outers_points, inners_points = cell_points_outers_inners if axes is None: axes = plt.axes() # Extract dimensions of the arrays n_words, n_word_bits, n_outers = outers_points.shape[:3] assert inners_points[:, :, 0, :].shape == outers_points[:, :, 0, :].shape n_inners = inners_points.shape[2] # Construct element control (settings) types. cell_inner_color = mcol.hex2color('#c0f8ff') hole_inner_color_0 = mcol.hex2color('#f8fcff') hole_inner_color_1 = mcol.hex2color('#c0a090') data = np.random.uniform(size=(n_words, n_word_bits)) data = (data > 0.7).astype(bool) elements = {} for i_row in range(n_words): for i_col in range(n_word_bits): # cell_inner_color = (float(i_row) / n_words, float(i_col) / n_word_bits, 0.0) cell_name = 'cell_{:03d}_{:03d}'.format(i_row, i_col) outer_name = 'outerpoly__{}'.format(cell_name) outerpoly = mpat.Polygon(outers_points[i_row, i_col], closed=True, edgecolor='black', linewidth=1.5, facecolor=cell_inner_color, zorder=2) elements[outer_name] = outerpoly inner_name = 'innerpoly__{}'.format(cell_name) bit_color = (hole_inner_color_1 if data[i_row, i_col] else hole_inner_color_0) innerpoly = mpat.Polygon(inners_points[i_row, i_col], closed=True, edgecolor='black', linewidth=1.5, facecolor=bit_color, zorder=4) elements[inner_name] = innerpoly for el in (outerpoly, innerpoly): axes.add_patch(el) return elements
def cmap(self, background_color='#000000', random_state=None): """ A matplotlib colormap consisting of random (muted) colors. This is very useful for plotting the segmentation image. Parameters ---------- background_color : str or `None`, optional A hex string in the "#rrggbb" format defining the first color in the colormap. This color will be used as the background color (label = 0) when plotting the segmentation image. The default is black. random_state : int or `~numpy.random.RandomState`, optional The pseudo-random number generator state used for random sampling. Separate function calls with the same ``random_state`` will generate the same colormap. """ from matplotlib import colors cmap = random_cmap(self.max + 1, random_state=random_state) if background_color is not None: cmap.colors[0] = colors.hex2color(background_color) return cmap
def set_styling(): sb.set_style("white") red = colors.hex2color("#bb3f3f") blue = colors.hex2color("#5a86ad") deep_colors = sb.color_palette("deep") green = deep_colors[1] custom_palette = [red, blue, green] custom_palette.extend(deep_colors[3:]) sb.set_palette(custom_palette) mpl.rcParams.update({"figure.figsize": np.array([6, 6]), "legend.fontsize": 12, "font.size": 16, "axes.labelsize": 16, "axes.labelweight": "bold", "xtick.labelsize": 16, "ytick.labelsize": 16})
def __setup_plot(self): gs = GridSpec(1, 2, width_ratios=[9.5, 0.5]) self.axes = self.figure.add_subplot(gs[0], projection='3d') numformatter = ScalarFormatter(useOffset=False) timeFormatter = DateFormatter("%H:%M:%S") self.axes.set_xlabel("Frequency (MHz)") self.axes.set_ylabel('Time') self.axes.set_zlabel('Level ($\mathsf{dB/\sqrt{Hz}}$)') colour = hex2color(self.settings.background) colour += (1,) self.axes.w_xaxis.set_pane_color(colour) self.axes.w_yaxis.set_pane_color(colour) self.axes.w_zaxis.set_pane_color(colour) self.axes.xaxis.set_major_formatter(numformatter) self.axes.yaxis.set_major_formatter(timeFormatter) self.axes.zaxis.set_major_formatter(numformatter) self.axes.xaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.zaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.set_xlim(self.settings.start, self.settings.stop) now = time.time() self.axes.set_ylim(utc_to_mpl(now), utc_to_mpl(now - 10)) self.axes.set_zlim(-50, 0) self.bar = self.figure.add_subplot(gs[1]) norm = Normalize(vmin=-50, vmax=0) self.barBase = ColorbarBase(self.bar, norm=norm, cmap=cm.get_cmap(self.settings.colourMap))
def make_colormap(name,absmax,zero_spread,n): if n < 2: raise ValueError("n > 1 requred.") # first we add some white padding #colors = [(0.5-zero_spread, "#FFFFFF"), (0.5, "#FFFFFF"), (0.5+zero_spread, "#FFFFFF")] colors = [(0.5, "#FFFFFF")] # make colornumbers cidx = [hexidx(i,n) for i in range(n)] ridx = [validx(0.0,0.5-zero_spread,i,0,n) for i in range(n)] ridx.reverse() bidx = [validx(0.5+zero_spread,0.5-zero_spread,i,1,n) for i in range(n)] # now we add colors reds = [color(255,c,c) for c in cidx] reds.reverse() blus = [color(c,c,255) for c in cidx] blus.reverse() # reds are negative so they are added here # from lightest to darkest cdict = dict(red=[], green=[], blue=[]) for item in zip(ridx,reds): colors.insert(0,item) for item in zip(bidx,blus): colors.append(item) # transfer colorarray to cdict for val,cc in colors: r,g,b = hex2color(cc) cdict['red'].append((val,r,r)) cdict['green'].append((val,g,g)) cdict['blue'].append((val,b,b)) return LinearSegmentedColormap(name, cdict)
def cmap(self, background_color='#000000', random_state=None): """ A matplotlib colormap consisting of random (muted) colors. This is very useful for plotting the segmentation image. Parameters ---------- background_color : str or `None`, optional A hex string in the "#rrggbb" format defining the first color in the colormap. This color will be used as the background color (label = 0) when plotting the segmentation image. The default is black. random_state : int or `~numpy.random.RandomState`, optional The pseudo-random number generator state used for random sampling. Separate function calls with the same ``random_state`` will generate the same colormap. """ from matplotlib import colors cmap = random_cmap(self.max_label + 1, random_state=random_state) if background_color is not None: cmap.colors[0] = colors.hex2color(background_color) return cmap
def modify_color(color_specifier, modifier): rgba = get_color_from_spec(color_specifier) if callable(modifier): return modifier(rgba) elif isinstance(modifier, str): if modifier=='dark': return tuple(c/2 for c in colors.hex2color(rgba)) elif modifier=='light': return tuple(1-(1-c)/2 for c in colors.hex2color(rgba)) elif modifier.startswith('alpha:'): alpha_val = float(modifier[len('alpha:'):]) return rgba[:3]+(alpha_val, ) else: raise NotImplementedError(modifier) elif modifier is not None: raise NotImplementedError(modifier)
def get_highlighed_color(self, color): rgb = mplcolors.hex2color(color) h, s, v = mplcolors.rgb_to_hsv(np.array(rgb).reshape(1, 1, 3)).reshape(3) v += 0.4 c = mplcolors.hsv_to_rgb((h, s, v)) return c
def cqgen(result, name='Output', color='#708090'): 'generate a .JSON file for ThreeJS objects.' # Open stream output = StringIO.StringIO() # cadquery will stream a ThreeJS JSON (using old v3 schema, which is deprecated) exporters.exportShape(result, 'TJS', output) # store stream to a variable contents = output.getvalue() # Close stream output.close() # Overwrite the JSON color portion with user color. Disallows NAMED colors col = list(colors.hex2color(color)) old_col_str = '"colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746]' new_col_str = '"colorDiffuse" : ' + str(col) new_contents = contents.replace(old_col_str, new_col_str) file_name = name + '.json' # Save the string to a json file with open(file_name, "w") as text_file: text_file.write(new_contents) # print "Part generated : " + file_name return
def change_hsv(c, h=None, s=None, v=None, frac=False): '''Quickly change the color in hsv space''' if isinstance(c, str): rgb = np.array([[ mc.hex2color(c), ]]) else: # rgb rgb = np.array([[ c[:3], ]]) hsv = mc.rgb_to_hsv(rgb) # print c # print rgb # print hsv for i, j in enumerate([h, s, v]): if j is not None: if frac: if j < 1: hsv[0][0][i] = hsv[0][0][i] * j else: hsv[0][0][i] = hsv[0][0][i] + \ (1 - hsv[0][0][i]) * (1 - j) else: hsv[0][0][i] = j return mc.hsv_to_rgb(hsv)[0][0]
def add_contour(self, position, contour, color): if is_color_like(color): color = hex2color(color) if color is None: color = hex2color(Colors.white) color = np.array(color) color = np.round(color*np.iinfo(self.dtype).max) # filter pixels that do not lie in the sub image contour = np.array(filter( lambda c: c[0]<self.swidth and c[1]<self.swidth, contour)) contour = contour + np.array((position*self.swidth, 0)) # rgb color according to dtype of the image self.contours.append((contour[:, 0], contour[:, 1], color))
def make_cmap(self, background_color='#000000', random_state=None): """ Define a matplotlib colormap consisting of (random) muted colors. This is very useful for plotting the segmentation array. Parameters ---------- background_color : str or `None`, optional A hex string in the "#rrggbb" format defining the first color in the colormap. This color will be used as the background color (label = 0) when plotting the segmentation array. The default is black ('#000000'). random_state : int or `~numpy.random.mtrand.RandomState`, optional The pseudo-random number generator state used for random sampling. Separate function calls with the same ``random_state`` will generate the same colormap. Returns ------- cmap : `matplotlib.colors.ListedColormap` The matplotlib colormap. """ from matplotlib import colors cmap = make_random_cmap(self.max_label + 1, random_state=random_state) if background_color is not None: cmap.colors[0] = colors.hex2color(background_color) return cmap
def border_color(color): r""" Parameters ---------- Returns ------- References ---------- Examples -------- """ r, g, b = clr.hex2color(clr.cnames[color]) colormap = {'red':((0.,0.,0.),\ (1.0,r,1.0)),\ 'green':((0.,0.,0.),\ (1.0,g,1.0)),\ 'blue':((0.,0.,0.),\ (1.0,b,1.0))} my_cmap = clr.LinearSegmentedColormap(color, colormap) return my_cmap
def make_cmap(self, background_color='#000000', seed=None): """ Define a matplotlib colormap consisting of (random) muted colors. This is very useful for plotting the segmentation array. Parameters ---------- background_color : str or `None`, optional A hex string in the "#rrggbb" format defining the first color in the colormap. This color will be used as the background color (label = 0) when plotting the segmentation array. The default is black ('#000000'). seed : int, optional A seed to initialize the `numpy.random.BitGenerator`. If `None`, then fresh, unpredictable entropy will be pulled from the OS. Separate function calls with the same ``seed`` will generate the same colormap. Returns ------- cmap : `matplotlib.colors.ListedColormap` The matplotlib colormap. """ from matplotlib import colors cmap = make_random_cmap(self.max_label + 1, seed=seed) if background_color is not None: cmap.colors[0] = colors.hex2color(background_color) return cmap
def showTopic(sender): topicModel = params['topicModel'] clear_output() labelProgressBar.value = '' topicID = topicSelector.value labelID = params['labels'].index(labelSelector.value) if chooseColor.value: c = colorSelector.value if not c.startswith('#'): c = cnames[c] hex_color = c rgb_color = hex2color(hex_color) else: rgb_color = tuple(params['colors'][topicSelector.value]) colorSelector.value = rgb2hex(rgb_color) temp = None if topicID == '' or labelID == '': print("Please check your input") else: drawTopicModel.drawFragmentsbyTopic(topicModel, topicID, n_top_frags=20, numRowsShown=1.2,\ numColumns=8, tableHeader='Top fragments of topic '+str(topicID)) drawTopicModel.drawMolsByTopic(topicModel, topicID, idsLabelToShow=[labelID], topicProbThreshold = 0.1, baseRad=0.9,\ numRowsShown=3, color=rgb_color)
def saveTopicAs(sender): topicModel = params['topicModel'] topicID = topicSelector.value labelID = params['labels'].index(labelSelector.value) path = filePath.value if chooseColor.value: c = colorSelector.value if not c.startswith('#'): c = cnames[c] hex_color = c rgb_color = hex2color(hex_color) else: rgb_color = tuple(params['colors'][topicSelector.value]) colorSelector.value = rgb2hex(rgb_color) temp = None if topicID == '' or labelID == '': print("Please check your input") else: svgGrid = drawTopicModel.generateSVGGridMolsbyTopic( topicModel, 0, idLabelToShow=labelID, topicProbThreshold=0.1, baseRad=0.9, color=rgb_color) with open(path + '.svg', 'w') as out: out.write(svgGrid) print("Saved topic image to: " + os.getcwd() + '/' + path + '.svg')
def sorted_color_maps(): '''List of color name and their hex values sorted by HSV. This code is taken from: http://matplotlib.org/examples/color/named_colors.html ''' colors_ = list(six.iteritems(colors.cnames)) # Add the single letter colors. for name, rgb in six.iteritems(colors.ColorConverter.colors): hex_ = colors.rgb2hex(rgb) colors_.append((name, hex_)) # Transform to hex color values. hex_ = [color[1] for color in colors_] # Get the rgb equivalent. rgb = [colors.hex2color(color) for color in hex_] # Get the hsv equivalent. hsv = [colors.rgb_to_hsv(color) for color in rgb] # Split the hsv values to sort. hue = [color[0] for color in hsv] sat = [color[1] for color in hsv] val = [color[2] for color in hsv] # Sort by hue, saturation and value. ind = np.lexsort((val, sat, hue)) sorted_colors = [colors_[i] for i in ind] sorted_colors = [ c_1 for (c_1, c_2) in zip(sorted_colors[:-1], sorted_colors[1:]) if c_1[1] != c_2[1]] return sorted_colors
def show_connection(img_name, coor, con): ''' Read the connection, coordinates and one image, draw the nodes and the connload_data_dict(dict_graph)ection on the image. ''' background = np.zeros((720, 1280, 3), np.uint8) background += 255 row_max, col_max = np.max(coor, axis=0) if row_max >= 720 or col_max >= 1280: for item in coor: item[0] /= 2 item[1] /= 2 color_list = [ 'hotpink', 'midnightblue', 'navy', 'plum', 'seagreen', 'black', 'purple', 'tan', 'wheat', 'chocolate' ] count = 0 for point in coor: t = colors.hex2color(colors.cnames[color_list[count]]) color = (int(t[0] * 255), int(t[1] * 255), int(t[2] * 255)) cv2.circle(background, (int(point[0]), int(point[1])), 5, color, (-1)) count += 1 for count in np.arange(con.shape[0]): cv2.line(background, (int(coor[con[count][0]][0]), int(coor[con[count][0]][1])), (int(coor[con[count][1]][0]), int(coor[con[count][1]][1])), (0, 0, 255), (1)) cv2.imshow(img_name, background) cv2.waitKey(0) cv2.destroyAllWindows()
def name2color(name): """Return the 3-element RGB array of a given color name.""" if '#' in name: h = name else: h = co.cnames[name].lower() return co.hex2color(h)
def reformat_dict(d): keys = d.keys() names = list() rgb = list() for k in keys: names.append(k) rgb.append(hex2color(d[k])) return {'names': names, 'rgb': np.array(rgb)}
def getcolor(spec): """ Turn optional color string spec into an array. """ if isinstance(spec, str): from matplotlib import colors return asarray(colors.hex2color(colors.cnames[spec])) else: return spec
def _color_tree(self, colour): if self.tree_selected is not None: c = col.hex2color(col.cnames[str(colour)]) print "coloring tree", colour, self.tree_selected for tree in self.tree_selected.get_all_trees(): tree.data["colour"] = c self.redraw_disconnectivity_graph()
def hex2rgb(color, mpl=False): """Return the rgb color as python int in the range 0-255.""" assert color.startswith("#") if mpl: fac = 1.0 else: fac = 255.0 rgb = [int(i*fac) for i in hex2color(color)] return tuple(rgb)
def bonds(molecule, sites=False, indices=False, faces=False, order=False, atomtypes=False, linewidth=4.): """Draw a 2d 'overhead' view of a molecule.""" fig = plt.figure() figTitle = molecule.name posList = molecule.posList length = len(molecule) for bond in molecule.bondList: i,j = bond plt.plot([posList[i][0],posList[j][0]], [posList[i][1],posList[j][1]], color='k', zorder=-1, linewidth=linewidth) cList = np.zeros([length,3]) if sites: for count in range(len(molecule)): cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]]) plt.scatter(posList[:,0],posList[:,1],s=1.5*radList[molecule.zList],c=cList, edgecolors='k') if indices: for index, pos in enumerate(molecule.posList): plt.annotate(index, (pos[0]+.1, pos[1]+.1), color='b', fontsize=10) if atomtypes: for atomtype, pos in zip(molecule.atomtypes, molecule.posList): plt.annotate(atomtype, (pos[0]-.5, pos[1]-.5), color='b', fontsize=10) if faces: for i,face in enumerate(molecule.faces): openAtoms = [x for x in face.atoms if x not in face.closed] plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2) plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red') plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s=40, c='purple') plt.annotate(i, (face.pos[0]-.35*face.norm[0], face.pos[1]-.35*face.norm[1]), color='r', fontsize=20) if np.linalg.norm(face.norm[:2]) > 0.0001: plt.quiver(face.pos[0]+.5*face.norm[0], face.pos[1]+.5*face.norm[1], 5.*face.norm[0], 5.*face.norm[1], color='r', headwidth=1, units='width', width=5e-3, headlength=2.5) if order: for index, bo in enumerate(molecule.bondorder): i,j = molecule.bondList[index] midpoint = (molecule.posList[i]+molecule.posList[j])/2. plt.annotate(bo, (midpoint[0], midpoint[1]), color='k', fontsize=20) fig.suptitle(figTitle, fontsize=18) plt.axis('equal') plt.xlabel('x-position', fontsize=13) plt.ylabel('y-position', fontsize=13) plt.show()