def custom_color(sample_to_label, samples_dendro_leaves, color_scale='Spectral'): # Sample label fragmentation sample_to_label = sample_to_label.astype(str).fillna('unkown') label_leaves = [str(sample_to_label[x]) for x in samples_dendro_leaves] uni_labels = list(np.unique(sample_to_label)) uni_len = len(uni_labels) uni_range = range(uni_len) uni_normal = [x/uni_range[-1] for x in uni_range] val_label = pd.Series(uni_range, index=uni_labels) val_set = [val_label[x] for x in label_leaves] colors = cl.scales[str(min(max(uni_len, 3), 11))]['div']['Spectral'] if uni_len > len(colors): if uni_len > 20: colors = cl.to_rgb(cl.interp(colors, 20)) for i in range(uni_len - 20): i = i % 20 colors.append(colors[i]) else: colors = cl.to_rgb(cl.interp(colors, uni_len)) colors_legend = [tuple(map(lambda x:x/255, x)) for x in cl.to_numeric(colors)] c_map_legend = list(zip(uni_range, colors_legend)) c_map = list(zip(uni_normal, colors)) return c_map, c_map_legend, val_set, val_label
def generate_cluster_colors(num): """Generate a list of colors given number needed. Arguments: num (int): Number of colors needed. n <= 35. Returns: list: strings containing RGB-style strings e.g. rgb(255,255,255). """ # Selects a random colorscale (RGB) depending on number of colors needed if num < 12: c = cl.scales[str(num)]['qual'] c = c[random.choice(list(c))] else: num_rounded = int(math.ceil(num / 10)) * 10 c = cl.to_rgb(cl.interp(cl.scales['12']['qual']['Paired'], num_rounded)) c = cl.to_numeric(sample(c, int(num))) # Converts selected colorscale to HSL, darkens the color if it is too light, # convert it to rgb string and return c_rgb = [] for color in c: hls = colorsys.rgb_to_hls(color[0] / 255, color[1] / 255, color[2] / 255) if hls[1] < 0.6: # Darkens the color if it is too light (HLS = [0]Hue [1]Lightness [2]Saturation) rgb = colorsys.hls_to_rgb(hls[0], 0.6, hls[2]) else: rgb = colorsys.hls_to_rgb(hls[0], hls[1], hls[2]) rgb_str = "rgb(" + str(rgb[0] * 255) + "," + str( rgb[1] * 255) + "," + str(rgb[2] * 255) + ")" c_rgb.append(rgb_str) return c_rgb
def get_singlecell_colors(cell_list, palette="paired", return_str=False): u_cells = list(set(cell_list)) color_list = cl.to_rgb(cl.interp(my_palette_dict[palette], len(u_cells))) if not return_str: color_list = [rgb_to_list(i) for i in color_list] group_colors = dict(zip(u_cells, color_list)) return group_colors
def graphs(self, explanations, pre_computed=False): """Convert exps list to graph locations and annotated text.""" import colorlover as cl order, color_order = [], {} for i, explanation in enumerate(explanations): explanation, probabilities, class_names = \ self.unwind(explanation, pre_computed) if not color_order: try: n_colors = cl.scales[str(len(class_names))]['qual']['Set2'] except KeyError: corrected_n = len(class_names) + 1 n_colors = cl.scales[str(corrected_n)]['qual']['Set2'] lime_colors = cl.to_rgb(n_colors) color_order = { name: color for color, name in zip(lime_colors, class_names) } colors = [color_order[name] for name in class_names] order.append([ self.prob_graph(i, probabilities, class_names, colors), self.weight_graph(i, explanation, colors), self.tag_text(i, explanation, colors) ]) return order
def create_k_clusters(k, X, text=''): """ Creates a list of scatter objects for clustering visualization Parameters: ---------------- k: int Number of clusters to fit data to X: numpy array n x 2 array with coordinates of each point text: string or array of strings Text which will pop up when hovering over data points Returns: ---------------- data: list of plotly.graph_objs.Scatter objects Contains Scatter objects for two dimensional plotting """ data = [] colors_k_bins = cl.to_rgb(cl.interp(cl.scales['11']['qual']['Paired'], k)) class_labels_k = KMeans(k).fit_predict(X) for i,j in enumerate(colors_k_bins): data.append(go.Scatter(x = X[class_labels_k==i,0], y = X[class_labels_k==i,1], text = text, mode = 'markers', marker=go.scatter.Marker(color=j) ) ) return data
def to_strings(self, n_bins=255, kind='rgb'): """Convert colormap to plotly-style strings. Parameters ---------- n_bins : int The number of bins in the output array kind : 'rgb' | 'husl' | 'hex' | 'name' Whether to return colors in rgb, husl, or hex format. Or, return the common name for that color if possible. Returns ------- colors_string : list of strings A list of "rgb()" or "hsl()" strings suitable for use in plotly. Or a list of hex strings for online plotting. Or a list of names associated with the colors. """ # Remove the alpha array = self.cmap(np.linspace(0, 1, n_bins))[:, :-1] if kind == 'hex': colors_string = [pl.husl.rgb_to_hex(ii) for ii in array] elif kind == 'name': colors_string = _get_color_names(array * 255.) else: array = array * 255. list_of_tups = [tuple(i) for i in array] if kind == 'rgb': colors_string = cl.to_rgb(list_of_tups) elif kind == 'husl': colors_string = cl.to_hsl(list_of_tups) return colors_string
def __init__(self, time_by_forces: ndarray, step_size: float): forces_by_time = np.array(time_by_forces).T motor_unit_count, steps = forces_by_time.shape sim_duration = steps * step_size times = np.arange(0.0, sim_duration, step_size) # Setting colors for plot. potvin_scheme = [ 'rgb(115, 0, 0)', 'rgb(252, 33, 23)', 'rgb(230, 185, 43)', 'rgb(107, 211, 100)', 'rgb(52, 211, 240)', 'rgb(36, 81, 252)', 'rgb(0, 6, 130)' ] # It's hacky but also sorta cool. c = cl.to_rgb(cl.interp(potvin_scheme, motor_unit_count)) c = [val.replace('rgb', 'rgba') for val in c] c = [val.replace(')', ',{})') for val in c] # Assing non-public attributes self._step_size = step_size self._forces_by_time = forces_by_time self._c = c self._times = times # Assign public attributes self.motor_unit_count = motor_unit_count
def graphs(self, explanations, pre_computed=False): """Convert exps list to graph locations and annotated text.""" import colorlover as cl order, color_order = [], {} for i, explanation in enumerate(explanations): explanation, probabilities, class_names = self.unwind(explanation, pre_computed) if not color_order: try: n_colors = cl.scales[str(len(class_names))]["qual"]["Set2"] except KeyError: corrected_n = len(class_names) + 1 n_colors = cl.scales[str(corrected_n)]["qual"]["Set2"] lime_colors = cl.to_rgb(n_colors) color_order = {name: color for color, name in zip(lime_colors, class_names)} colors = [color_order[name] for name in class_names] order.append( [ self.prob_graph(i, probabilities, class_names, colors), self.weight_graph(i, explanation, colors), self.tag_text(i, explanation, colors), ] ) return order
def interp(colors,N): def _interp(colors,N): try: return cl.interp(colors,N) except: return _interp(colors,N+1) c=_interp(colors,N) return list(map(rgb_to_hex,cl.to_rgb(c)))
def get_spaced_colors(n, randomized=False): if n > 0: max_value = 255 interval = max_value / n hues = np.arange(0, max_value, interval) return cl.to_rgb(["hsl(%d,80%%,40%%)" % i for i in hues]) else: return None
def get_plot_colors(max_colors, color_format="pyplot"): """Generate colors for plotting.""" colors = cl.scales["11"]["qual"]["Paired"] if max_colors > len(colors): colors = cl.to_rgb(cl.interp(colors, max_colors)) if color_format == "pyplot": return [[j / 255.0 for j in c] for c in cl.to_numeric(colors)] return colors
def get_plot_colors(max_colors, color_format='pyplot'): """Generate colors for plotting.""" colors = cl.scales['11']['qual']['Paired'] if max_colors > len(colors): colors = cl.to_rgb(cl.interp(colors, max_colors)) if color_format == 'pyplot': return [[j / 255.0 for j in c] for c in cl.to_numeric(colors)] return colors
def to_color(self, value): if self._max == self._min: return "#fffffff" pct = (value - self._min) / (self._max - self._min) bin_no = max(min(int(pct * self._n), self._n - 1), 0) color = self._scheme[bin_no] r, g, b = colorlover.to_numeric(colorlover.to_rgb([color]))[0] hexval = "#{0:02x}{1:02x}{2:02x}".format(int(r), int(g), int(b)) return hexval
def get_color_pool(n): if n <= 12: return cl.scales['12']['qual']['Paired'] color_pool = [] for i in np.arange(60., 360., 360. / n): hue = i / 300. rand_num = np.random.random_sample() lightness = (50 + rand_num * 10) / 100. saturation = (90 + rand_num * 10) / 100. rgb = hls_to_rgb(hue, lightness, saturation) color_pool.append(tuple([int(x * 255) for x in rgb])) return cl.to_rgb(color_pool)
def continuous_color_pool(n): from colorsys import hls_to_rgb color_pool = [] for i in np.arange(60., 360., 360. / n): hue = i / 300. rand_num = np.random.random_sample() additive = rand_num * 10 lightness = (50 + additive) / 100. saturation = (85 + additive) / 100. rgb = hls_to_rgb(hue, lightness, saturation) color_pool.append(tuple([int(x * 255) for x in rgb])) return colorlover.to_rgb(color_pool)
def __call__(self, data, kind='rgb', as_string=False, vmin=None, vmax=None): """Convert a subset of colors to a given type. Parameters ---------- data : array, shape (n_colors,) Must be an array of floats between 0 and 1. These will be used to index into self.cmap. kind : 'rgb' | 'husl' | 'html' Whether to return output colors in rgb or husl space. If 'html', the color output of the call will be displayed. as_string : bool If True, return colors as plotly-style strings. Returns ------- arr : np.array | list of strings The colors associated with values in `frac`. """ data = np.atleast_1d(data) if data.ndim > 1: raise ValueError('frac must be 1-d') if vmin is not None or vmax is not None: # If we need to scale out data frac = np.clip((data - vmin) / float(vmax - vmin), 0, 1) else: frac = data if not ((frac >= 0.) * (frac <= 1.)).all(0): raise ValueError('input must be between 0 and 1, you' ' provided {}'.format(frac)) arr = self.cmap(frac) if kind == 'rgb': if as_string is False: pass else: arr = [tuple(i) for i in arr[:, :-1] * 255] arr = cl.to_rgb(arr) elif kind == 'husl': if as_string is False: arr = np.array([pl.husl.rgb_to_husl(r, g, b) for r, g, b, _ in arr]) else: arr = [tuple(i) for i in arr[:, :-1] * 255] arr = cl.to_hsl(arr) elif kind == 'html': arr = [tuple(i) for i in arr[:, :-1] * 255] arr = cl.to_hsl(arr) arr = HTML(cl.to_html(arr)) else: raise ValueError("Kind {} not supported".format(kind)) return arr
def color_palette(elements, ptype='qual', palette='Paired'): n_element = len(elements) if n_element < 3: colors = cl.scales['3'][ptype][palette][:n_element] elif n_element <= 11: cnt = str(n_element) colors = cl.scales[cnt][ptype][palette] else: cnt = '11' palettes = cl.scales[cnt][ptype][palette] colors = cl.interp(palettes, n_element) colors = cl.to_rgb(colors) return dict(zip(elements, colors))
def color_scale_interp( input_num, max_num, min_num, color_mesh_size=80, hex_mode=True, ): """ """ # | - color_scale_interp # cl.scales["8"]["seq"]["Purples"] black_white_cs = [ 'rgb(0,0,0)', 'rgb(255,255,255)', ] black_red_cs = [ 'rgb(0,0,0)', 'rgb(255,0,0)', ] color_scale_i = black_red_cs color_scale_i = cl.scales["8"]["seq"]["Greys"][::-1] # color_scale_i = cl.scales["8"]["seq"]["Purples"] # color_scale_i = cl.scales['3']['div']['RdYlBu'] color_scale = cl.interp( color_scale_i, color_mesh_size, ) color_scale = cl.to_rgb(color_scale) # Converting RGB string representatino to tuple color_scale = cl.to_numeric(color_scale) input_norm = ((input_num - min_num) / (max_num - min_num)) cs_index = round(input_norm * len(color_scale)) - 1 if cs_index == -1: cs_index = 0 color_out = color_scale[cs_index] if hex_mode: color_out = rgb_to_hex(color_out) return (color_out)
def setColorSet(self, dimensions='12', type='qual', dataset='Paired'): if dimensions in cl.scales: if type in cl.scales[dimensions]: if dataset in cl.scales[dimensions][type]: color_set = cl.scales[dimensions][type][dataset] self.colorset = (dimensions, type, dataset) if (len(self.data.components) > len(color_set)): color_set = cl.interp(color_set, len(self.data.components)) color_set = cl.to_rgb(color_set) for i, component in enumerate(self.data.components): self.data.get_component(component).color = color_set[i] return True return False
def cache_raw_data(net_type, N=25, p=0.5, m=3, k=3): global model, data2, end, colors_c, stocks, initiated, agents if m >= N: N = m + 1 agents = fresh_agents if N >= len(fresh_agents) else fresh_agents[0:N] agents = [deepcopy(x) for x in agents] model = FinNetwork("Net 1", agents, net_type=net_type, p=p, m=m, k=k) stocks = [x.name for x in agents] colors_ = (cl.to_rgb( cl.interp(cl.scales['6']['qual']['Set1'], len(stocks) * 20))) colors_c = np.asarray(colors_)[np.arange(0, len(stocks) * 20, 20)] end = datetime.date.today() print('Loaded raw data') return 'loaded'
def palette_de_couleurs(nb_of_colors): """ Input: the length of the list with different colors Output: a list with rgb colors in an ascending order """ bupu = cl.scales['9']['seq']['Reds'] bupu500 = cl.interp( bupu, nb_of_colors ) # Map color scale to 500 bins colors=cl.to_rgb(bupu500) for i in range(nb_of_colors): color= colors[i][3:] c=array((0,0,0)) for j in range(3): c[j]=color.strip("()").split(",")[j] colors[i]=c return colors
def plot_spectrum(dataframe): """ Function used to plot a dataframe using Plotly. Uses colorlover to generate palettes. Args: dataframe - pandas dataframe containing a frequency column. Every other column is treated as an intensity column """ plots = list() keys = [key for key in dataframe.keys() if key != "Frequency"] if len(keys) < 3: # If there are fewer than 3 plots, colorlover doesn't have # a coded case and so the colors are done manually color_palette = ["#e41a1c", "#377eb8"] else: # Use color lover palettes color_palette = cl.to_rgb(cl.scales[str(len(keys))]["qual"]["Set1"]) for key, color in zip(keys, color_palette): # Loop over all the dataframe columns and colors plots.append( go.Scatter( x=dataframe["Frequency"], y=dataframe[key], name=key, marker={"color": color}, )) layout = go.Layout( xaxis={ "title": "Frequency (MHz)", "tickformat": "0.2f" }, yaxis={"title": ""}, autosize=False, height=800, width=1000, paper_bgcolor="#f0f0f0", plot_bgcolor="#f0f0f0", ) fig = go.Figure(data=plots, layout=layout) iplot(fig) return fig
def get_color_pool(n): # https://plot.ly/ipython-notebooks/color-scales/ import colorlover if n <= 8: if n <= 3: n = 3 return colorlover.scales[str(n)]['qual']['Set2'] if n <= 12: return colorlover.scales[str(n)]['qual']['Set3'] import random random.seed(666) def get_random_color(pastel_factor=0.5): return [(x + pastel_factor) / (1.0 + pastel_factor) for x in [random.uniform(0, 1.0) for i in [1, 2, 3]]] def color_distance(c1, c2): return sum([abs(x[0] - x[1]) for x in zip(c1, c2)]) def generate_new_color(existing_colors, pastel_factor=0.5): max_distance = None best_color = None for i in range(0, 100): color = get_random_color(pastel_factor=pastel_factor) # exclude some colors if np.absolute(np.array(color) - np.array([1, 1, 1])).sum() < 0.08: continue if not existing_colors: return color best_distance = min( [color_distance(color, c) for c in existing_colors]) if not max_distance or best_distance > max_distance: max_distance = best_distance best_color = color return best_color color_pool = [] for i in range(0, n): color_pool.append(generate_new_color(color_pool, pastel_factor=0.9)) color_pool = [(int(x * 255), int(y * 255), int(z * 255)) for x, y, z in color_pool] color_pool = sorted(color_pool, key=lambda x: (x[0], x[1], x[2])) return colorlover.to_rgb(color_pool)
def plotPrettyColours(data, grouping): #make directories for saving plot htmls os.makedirs(clustering_evaluation_dir, exist_ok=True) os.makedirs(cluster_analysis_dir, exist_ok=True) if grouping == 'experiments': colour_seq = ['Reds','Oranges','YlOrBr','YlGn','Greens','BuGn','Blues','RdPu', 'PuBu','Purples','PuRd','YlGnBu','YlOrRd'] df = pd.DataFrame(data.experiment_name.unique(), columns=['name']) df['root'] = df.applymap(lambda x: '_'.join(x.split('_',2)[0:2])) elif grouping == 'elec_bin': colour_seq = ['YlGn','PuRd','Blues','YlOrBr','Greens','RdPu','Oranges', 'Purples','PuBu','BuGn','Reds'] df = data['elec_bin'].reset_index().rename({'elec_bin':'root', 'k':'name'}, axis=1) df['root'] = df.root.astype('category') df.root.cat.rename_categories(colour_seq[:len(df.root.cat.categories)], inplace=True) col_temp = df.groupby('root').apply(lambda x: len(x)) my_cols = list() for c, v in col_temp.items(): try: i = 0 gcol=list() while i < v: gcol.append(cl.scales['9']['seq'][c][2+i]) i+=1 except: i = 0 gcol=list() jump = int(80/v) while i < v: gcol.append(cl.to_rgb(cl.interp(cl.scales['9']['seq'][c], 100))[-1-jump*i]) i+=1 my_cols+=gcol colours = dict(zip(df.name, my_cols)) return colours
def get_group_colors(metadata, group_by="CellType", palette="paired", return_str=False, return_hex=False): assert group_by in metadata.columns.tolist(), "Invalid group_by value." assert palette in list(my_palette_dict.keys()), "Invalid palette name." u_groups = sorted(list(set(metadata[group_by]))) color_list = cl.to_rgb(cl.interp(my_palette_dict[palette], len(u_groups))) if return_str and return_hex: color_list = [rgb_to_hex(i) for i in color_list] if not return_str: color_list = [rgb_to_list(i) for i in color_list] group_colors = dict(zip(u_groups, color_list)) if "Others" in u_groups: if not return_str: group_colors["Others"] = rgb_to_list('rgb(128, 128, 128)') elif return_str and return_hex: group_colors["Others"] = '#808080' else: group_colors["Others"] = 'rgb(128, 128, 128)' return group_colors
def scatter_plot_color(data_df): """Builds scatter plot traces given a data frame containing x, y and grp data Args: data: A data frame containin the following columns x - Data for the x axis y - Data for the y axis grp - group indicators Returns: A list of traces to plot with plotly """ clrs = np.array(cl.scales['12']['qual']['Paired']) # Determine unique groups and map them to ints unique_grps = np.unique(data_df['grp']) num_grps = len(unique_grps) grp_nums = np.array(range(num_grps)) if num_grps > 12: clrs = cl.to_rgb(cl.interp(clrs, num_grps)) # Map the given groups to their corresponding ints grp_inds = grp_nums[um.match_arrays(np.array(data_df['grp']), unique_grps)] # Add column for colour plot_data_df = data_df plot_data_df['clr'] = clrs[grp_inds] # Create a scatter plot trace for each group, coloring them differently traces = [] for i in unique_grps: inds = np.where(plot_data_df['grp'] == i)[0] trace0 = get_scatter_plot_trace_color_grp(plot_data_df.iloc[inds, :]) traces.append(trace0) return traces
def get_color_pool(n, bright=0.5, continuous=False): """ :param n: expected color number :param bright: brightness of color :param continuous: if to generate a continuous color list :return: color list, in rgb mode """ random.seed(666) np.random.seed(666) if bright > 1 or bright < 0: raise Exception('bright should be in range [0, 1]') if continuous: return continuous_color_pool(n) if n < 13: if bright < 0.5: style = False else: style = True return colorlover_pool(n, light=style) color_pool = [] if n < 20: cutoff = 0.2 elif n < 50: cutoff = 0.15 elif n < 100: cutoff = 0.1 elif n < 200: cutoff = 0.02 else: cutoff = 0.0001 for i in range(0, n): color_pool.append( generate_new_color(color_pool, pastel_factor=bright, cutoff=cutoff)) color_pool = [(int(x * 255), int(y * 255), int(z * 255)) for x, y, z in color_pool] color_pool = sorted(color_pool, key=lambda x: (x[0], x[1], x[2])) return colorlover.to_rgb(color_pool)
def viewSection(width=800, height=400, cs=None, dnlay=None, rangeX=None, rangeY=None, linesize=3, title='Cross section'): """ Plot multiple cross-sections data on a graph. Parameters ---------- variable: width Figure width. variable: height Figure height. variable: cs Cross-sections dataset. variable: dnlay Layer step to plot the cross-section. variable: rangeX, rangeY Extent of the cross section plot. variable: linesize Requested size for the line. variable: title Title of the graph. """ nlay = len(cs.secDep) colors = cl.scales['9']['div']['BrBG'] hist = cl.interp(colors, nlay) colorrgb = cl.to_rgb(hist) trace = {} data = [] trace[0] = Scatter(x=cs.dist, y=cs.secDep[0], mode='lines', line=dict(shape='line', width=linesize + 2, color='rgb(0, 0, 0)')) data.append(trace[0]) for i in range(1, nlay - 1, dnlay): trace[i] = Scatter(x=cs.dist, y=cs.secDep[i], mode='lines', line=dict(shape='line', width=linesize, color='rgb(0,0,0)'), opacity=0.5, fill='tonexty', fillcolor=colorrgb[i]) data.append(trace[i]) trace[nlay - 1] = Scatter(x=cs.dist, y=cs.secDep[nlay - 1], mode='lines', line=dict(shape='line', width=linesize + 2, color='rgb(0, 0, 0)'), fill='tonexty', fillcolor=colorrgb[nlay - 1]) data.append(trace[nlay - 1]) trace[nlay] = Scatter(x=cs.dist, y=cs.secDep[0], mode='lines', line=dict(shape='line', width=linesize + 2, color='rgb(0, 0, 0)')) data.append(trace[nlay]) if rangeX is not None and rangeY is not None: layout = dict(title=title, font=dict(size=10), width=width, height=height, showlegend=False, xaxis=dict(title='distance [m]', range=rangeX, ticks='outside', zeroline=False, showline=True, mirror='ticks'), yaxis=dict(title='elevation [m]', range=rangeY, ticks='outside', zeroline=False, showline=True, mirror='ticks')) else: layout = dict(title=title, font=dict(size=10), width=width, height=height) fig = Figure(data=data, layout=layout) plotly.offline.iplot(fig) return
def viewSections(width = 800, height = 400, cs = None, layNb = 2, linesize = 3, title = 'Cross section'): """ Plot multiple cross-sections data on a graph. Parameters ---------- variable: width Figure width. variable: height Figure height. variable: cs Cross-sections dataset. variable: layNb Number of layer to plot. variable: linesize Requested size for the line. variable: title Title of the graph. """ colors = cl.scales['9']['div']['RdYlBu'] hist = cl.interp( colors, layNb ) colorrgb = cl.to_rgb( hist ) nlay = layNb - 1 lay = {} toplay = cs[nlay].top cs[nlay].ndepo = cs[nlay].depo cs[nlay].ntop = toplay botlay = cs[nlay].top - cs[nlay].depo for i in range(nlay-1,-1,-1): tmp1 = cs[i+1].ndepo - cs[i].depo tmp2 = cs[i+1].ndepo - tmp1.clip(min=0) cs[i].ndepo = tmp2 cs[i].ntop = botlay + tmp2 trace = {} data = [] for i in range(1,nlay): trace[i-1] = Scatter( x=cs[i].dist, y=cs[i].ntop, mode='lines', name="layer "+str(i), line=dict( shape='line', width = linesize-1, color = colorrgb[i-1] #, #dash = 'dash' ) ) data.append(trace[i-1]) # Top line trace[nlay] = Scatter( x=cs[nlay].dist, y=cs[nlay].top, mode='lines', name="top", line=dict( shape='line', width = linesize, color = 'rgb(102, 102, 102)' ) ) data.append(trace[nlay]) # Bottom line trace[nlay+1] = Scatter( x=cs[nlay].dist, y=cs[nlay].top - cs[nlay].depo, mode='lines', name="base", line=dict( shape='line', width = linesize, color = 'rgb(102, 102, 102)' ) ) data.append(trace[nlay+1]) layout = dict( title=title, width=width, height=height ) fig = Figure(data=data, layout=layout) plotly.offline.iplot(fig) return
def test_to_rgb(self): scales = cl.to_rgb(cl.scales['3']['div']['RdYlBu']) self.assertEqual( scales, ['rgb(252,141,89)', 'rgb(255,255,191)', 'rgb(145,191,219)'] )
def genLocationFigure(xCfgAircraft, xCfgAirlines): ######################################## ######################################## selectedAirlines = xCfgAirlines.get('airlines', dataModule.Airlines) selectedAircraft = xCfgAircraft routes = dataModule.filterData(dataModule.Airports, selectedAirlines, selectedAircraft) YlOrRd = cl.scales['9']['seq']['YlOrRd'] clrscale = cl.to_rgb(cl.interp(YlOrRd, 10)) layers = [] totallines = 0 #For visualization, we can drop any city pairs regardless of airlines/aircraft/etc. for i, (srcCnt, df1) in enumerate(routes.groupby(['srcCountry'])): line_features = [] col = clrscale[i % len(clrscale)] if totallines > 1000 / 20: log.warning( 'Reached maximum number of lines that should be drawn ...') break for destCnt, df in df1.groupby('destCountry'): totallines += 1 #only consider international flights # if(destCnt == srcCnt) : continue for x, row in df.iterrows(): # row = dict( # srcLat = (df['srcLat']), # srcLon = (df['srcLon']), # destLat = (df['destLat']), # destLon = (df['destLon']) # ) line = { "type": "Feature", "geometry": { "type": "LineString", "coordinates": geoline([row['srcLon'], row['srcLat']], [row['destLon'], row['destLat']]) }, } line_features.append(line) geojsonDict = {'type': 'FeatureCollection', 'features': line_features} layers += [ dict( sourcetype='geojson', source=geojsonDict, color=col, type='line', #line= {'width': 1}, opacity=.2) ] # for i, (airline, df) in enumerate(routes.groupby('airline')): # col = clrscale[i % len(clrscale)] # if totallines > 2000: # log.warning('Reached maximum number of lines that should be drawn ...') # break # line_features = [] # for j , (index, row) in enumerate(df.iterrows()): # totallines += 1 # if j > 10: # break # line = { "type": "Feature", # "geometry": { # "type": "LineString", # "coordinates": [[row['srcLon'], row['srcLat']], [row['destLon'], row['destLat']]] # } # } # line_features.append(line) # geojsonDict = {'type': 'FeatureCollection', # 'features': line_features} # layers += [dict(sourcetype = 'geojson', # source = geojsonDict, # color= col, # type = 'line', # line= {'width': 1}, # opacity=.3 # ) # ] data = [{'type': 'scattermapbox'}] layout = dict( uirevision=True, title='World View', hoverlabel={ 'bordercolor': '#117a86', 'bgcolor': 'white', 'font': { 'family': 'Open Sans', 'size': '16', 'color': '#117a86', } }, titlefont={ 'size': 16, 'color': '#a8a8a8', 'family': 'Open Sans' }, xaxis={ 'showgrid': False, 'showticklabels': False, 'visible': False }, yaxis={ 'showgrid': False, 'showticklabels': False, 'visible': False }, showlegend=False, hovermode='closest', autosize=False, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='#92d7ea', margin={ 't': 40, 'b': 0, 'r': 0, 'l': 0, 'pad': 1 }, dragmode='pan', clickmode='event+select', # updatemenus = getUpdateMenus(), mapbox=dict( uirevision=True, accesstoken=mapboxtoken, style='dark', bearing=0, center=dict(lat=0, lon=0), pitch=0, zoom=.5, layers=layers, ), ) fig = dict(data=data, layout=layout) return fig
def get_heat_colors(n): max_value = 255 interval = int(max_value / n) hues = range(0, max_value, interval) return cl.to_rgb(["hsl(%d,100%%,40%%)" % i for i in hues])
def get_color_scale(df=None, dx=None): """ """ # ############################################################################# # Using built in colormaps #################################################### c = cmaps.Colormap() CM_i = c.cmap("viridis") color_pall_tmp = CM_i(np.linspace(0, 1., num=200), alpha=0.6) color_pall_tmp2 = [] for i in color_pall_tmp: color_i = "rgba(" + \ str(255 * i[0]) + "," + \ str(255 * i[1]) + "," + \ str(255 * i[2]) + "," + \ str(i[3]) + \ ")" color_pall_tmp2.append(color_i) color_pall_0 = color_pall_tmp2 # ############################################################################# # ############################################################################# # ############################################################################# # Defining custom colormap # color_pall = cl.scales['9']['seq']['BuPu'][::-1][2:-1] color_pall_1 = [ # Grey scale gradient hex_to_rgb("d5d5d5d1"), # Lighter hex_to_rgb("929292d1"), # Darker # hex_to_rgb("afafafd1"), # hex_to_rgb("1f1f1fd1"), # ##################################################################### # hex_to_rgb("b6d935d1"), # hex_to_rgb("e07a58d1"), # hex_to_rgb("c9c9c9"), # hex_to_rgb("6e6e6e"), # hex_to_rgb("afafafd1"), # hex_to_rgb("1f1f1fd1"), # "rgb(175,175,175)", # "rgb(31,31,31)", ] # # color_pall = color_pall_1 # ############################################################################# # ############################################################################# # ############################################################################# color_pall_interp = cl.interp(color_pall, 80) # Map color scale to 500 bins color_pall_interp_new = [] for color_i in color_pall_interp: color_i = color_i.replace("%", "") color_i = color_i.replace(" ", "") color_pall_interp_new.append(color_i) color_pall_interp = color_pall_interp_new color_pall_interp = cl.to_rgb(color_pall_interp) # ############################################################################# num_bins = len(color_pall_interp) d_step = (1 / (num_bins - 1)) custom_color_pall_final = [] for i_cnt, color_i in enumerate(color_pall_interp): custom_color_pall_final.append([i_cnt * d_step, color_i]) #print(custom_color_pall_final) colorscale_i = custom_color_pall_final # ############################################################################# # ############################################################################# # ############################################################################# # COMBAK AB2/3 have the same min/max ave. coord. so this works, but otherwise we would have to do it separately for each stoich (I think) stoich = "AB2" df_i = df[df.stoich == stoich] z_min = df_i.mean_coor.min() z_max = df_i.mean_coor.max() b = z_min m = (z_max - z_min) / 1. color_tmp = "grey" special_coord_dict = { # Blue and green 4: dict(color=hex_to_rgb("d93535d1")), 6: dict(color=hex_to_rgb("35c0d9d1")), # Blue and green # 4: dict(color=hex_to_rgb("3cc9e3ff")), # 6: dict(color=hex_to_rgb("a4e168ff")), # 4: dict(color=hex_to_rgb("afafafd1")), # 6: dict(color=hex_to_rgb("1f1f1fd1")), } for coord_i, val in special_coord_dict.items(): spec_color_i = val["color"] lower_bound = (coord_i - dx - b) / m upper_bound = (coord_i + dx - b) / m # ############################################################################# for i_cnt, color_i in enumerate(colorscale_i): scale_pos_i = color_i[0] if scale_pos_i > lower_bound: lower_bound_ind = i_cnt break # ############################################################################# for i_cnt, color_i in enumerate(colorscale_i): scale_pos_i = color_i[0] if scale_pos_i > upper_bound: upper_bound_ind = i_cnt break del colorscale_i[lower_bound_ind:upper_bound_ind] colorscale_i.insert(lower_bound_ind, [(coord_i + dx - b) / m, spec_color_i]) colorscale_i.insert(lower_bound_ind, [(coord_i - b) / m, spec_color_i]) colorscale_i.insert(lower_bound_ind, [(coord_i - dx - b) / m, spec_color_i]) return (colorscale_i)
for i in np.arange(60., 360., 360. / n): hue = i / 300. rand_num = np.random.random_sample() lightness = (50 + rand_num * 10) / 100. saturation = (90 + rand_num * 10) / 100. rgb = hls_to_rgb(hue, lightness, saturation) color_pool.append(tuple([int(x * 255) for x in rgb])) return cl.to_rgb(color_pool) # 随机生成100不同的颜色 n = 100 p = [tuple(x) for x in np.random.choice(range(10, 250), (n, 3))] p = list(set(p)) p.sort(key=lambda x: x) color_pool = cl.to_rgb(p[::-1]) # 获取12个漂亮的颜色 color_pool = cl.scales['12']['qual']['Paired'] def ucsc2gencode(infile): return dict(x.strip().split()[:2] for x in open(infile)) def replace_ucsc_with_gencode(infile, outfile, convert_file='GRCh38_UCSC2gencode.txt'): convert_dict = ucsc2gencode(convert_file) with open(infile) as fr, open(outfile, 'w') as fw: for line in fr:
def viewSection(width = 800, height = 400, cs = None, dnlay = None, rangeX = None, rangeY = None, linesize = 3, title = 'Cross section'): """ Plot multiple cross-sections data on a graph. Parameters ---------- variable: width Figure width. variable: height Figure height. variable: cs Cross-sections dataset. variable: dnlay Layer step to plot the cross-section. variable: rangeX, rangeY Extent of the cross section plot. variable: linesize Requested size for the line. variable: title Title of the graph. """ nlay = len(cs.secDep) colors = cl.scales['9']['div']['BrBG'] hist = cl.interp( colors, nlay ) colorrgb = cl.to_rgb( hist ) trace = {} data = [] trace[0] = Scatter( x=cs.dist, y=cs.secDep[0], mode='lines', line=dict( shape='line', width = linesize+2, color = 'rgb(0, 0, 0)' ) ) data.append(trace[0]) for i in range(1,nlay-1,dnlay): trace[i] = Scatter( x=cs.dist, y=cs.secDep[i], mode='lines', line=dict( shape='line', width = linesize, color = 'rgb(0,0,0)' ), opacity=0.5, fill='tonexty', fillcolor=colorrgb[i] ) data.append(trace[i]) trace[nlay-1] = Scatter( x=cs.dist, y=cs.secDep[nlay-1], mode='lines', line=dict( shape='line', width = linesize+2, color = 'rgb(0, 0, 0)' ), fill='tonexty', fillcolor=colorrgb[nlay-1] ) data.append(trace[nlay-1]) trace[nlay] = Scatter( x=cs.dist, y=cs.secDep[0], mode='lines', line=dict( shape='line', width = linesize+2, color = 'rgb(0, 0, 0)' ) ) data.append(trace[nlay]) if rangeX is not None and rangeY is not None: layout = dict( title=title, font=dict(size=10), width=width, height=height, showlegend = False, xaxis=dict(title='distance [m]', range=rangeX, ticks='outside', zeroline=False, showline=True, mirror='ticks'), yaxis=dict(title='elevation [m]', range=rangeY, ticks='outside', zeroline=False, showline=True, mirror='ticks') ) else: layout = dict( title=title, font=dict(size=10), width=width, height=height ) fig = Figure(data=data, layout=layout) plotly.offline.iplot(fig) return
def test_to_rgb(self): scales = cl.to_rgb(cl.scales['3']['div']['RdYlBu']) self.assertEqual( scales, ['rgb(252,141,89)', 'rgb(255,255,191)', 'rgb(145,191,219)'])
def createFigureWidget(self): dimensions = self.dimensions data_lines = [] nodes = [{} for dim in dimensions] values = [] colors = [] traces = [] if self.options['colorscale'].value == GlueParallelCategoriesPlotly.default_color: color_set = [self.data.get_component(dim).color for dim in dimensions] else: color_set = cl.scales['8']['qual'][self.options['colorscale'].value] if (len(self.dimensions) > 8): color_set = cl.interp( color_set, len(dimensions) ) color_set = cl.to_rgb(color_set) for i, dimension in enumerate(dimensions): dvalues = np.unique(self.data[dimension].flatten()) if len(dvalues) < self.options['grouping_limit'].value or hasattr(self.data[dimension].flatten(), 'codes'): nodes[i]['values'] = np.unique(self.data[dimension].flatten()) nodes[i]['masks'] = [] for val in nodes[i]['values']: nodes[i]['masks'].append(self.data[dimension] == val) else: hist, bin_edges = np.histogram(self.data[dimension].flatten(), bins='auto') if (len(bin_edges) > self.options['grouping_limit'].value): hist, bin_edges = np.histogram(self.data[dimension].flatten(), bins=self.options['grouping_limit'].value) nodes[i]['values'] = [] for edge in range(len(bin_edges)-1): nodes[i]['values'].append( "{:.1f}".format(bin_edges[edge]) + " - " + "{:.1f}".format(bin_edges[edge+1])) nodes[i]['masks'] = [] for edge in range(len(bin_edges)-1): if edge == 0: nodes[i]['masks'].append((self.data[dimension] >= bin_edges[edge]) & (self.data[dimension] <= bin_edges[edge+1])) else : nodes[i]['masks'].append((self.data[dimension] > bin_edges[edge]) & (self.data[dimension] <= bin_edges[edge+1])) line = {} line['values'] = np.array(['' for i in range(self.data.size)], dtype = 'object') colorv = np.array(['#EEEEEE' for i in range(self.data.size)]) for k, value in enumerate(nodes[i]['values']): mask = nodes[i]['masks'][k] line['values'][mask] = value for sset in self.data.subsets: if hasattr(sset,"disabled") == False or sset.disabled == False: sset_mask = sset.to_mask() color = sset.style.color colorv[mask & sset_mask] = color mask = mask & ~sset_mask colors.extend(colorv) line['values'] = line['values'].tolist() line['label'] = dimension data_lines.append(line); parcats = { 'type' : 'parcats', 'dimensions' : data_lines, 'line' : { 'color' : colors, 'shape': 'hspline' } } traces.append(parcats) layout = { 'title' : self.options['title'].value, 'xaxis': { 'title' : self.options['xaxis'].value, 'range' : [0,1], 'showgrid':False, 'showline':False, 'showticklabels':False, 'zeroline':False }, 'yaxis': { 'title' : self.options['yaxis'].value, 'range' : [0,1], 'showgrid':False, 'showline':False, 'showticklabels':False, 'zeroline':False }, 'showlegend': self.margins['showlegend'].value, 'legend' : { 'orientation' : self.margins['legend_orientation'].value, 'x' : self.margins['legend_xpos'].value, 'y' : self.margins['legend_ypos'].value } } if self.only_subsets == False: trace = { 'type': "scatter", 'name' : self.data.label, 'textposition' : 'middle right', 'x' : [-1000], 'y' : [i], 'mode' : 'markers', 'marker': { 'color' : "#EEEEEE", 'size' : 20, 'line': { 'width': 0, }, 'symbol' : 'square' } } traces.append(trace) for sset in self.data.subsets: color = sset.style.color trace = { 'type': "scatter", 'name' : sset.label, 'textposition' : 'middle right', 'x' : [-1000], 'y' : [i], 'mode' : 'markers', 'marker': { 'color' : color, 'size' : 20, 'line': { 'width': 0, }, 'symbol' : 'square' } } traces.append(trace) data = traces FigureWidget(data = data, layout = layout) return FigureWidget(data = data, layout = layout)