def to_rgb_color_list(color_str, default): if "rgb" in color_str: return [int(v) for v in color_str.strip("rgb()").split(",")] elif "#" in color_str: return clrs.hex_to_rgb(color_str) else: return default
def to_rgb_color_list(color_str, default): if 'rgb' in color_str: return [int(v) for v in color_str.strip('rgb()').split(',')] elif '#' in color_str: return clrs.hex_to_rgb(color_str) else: return default
def _colors(ncontours, colormap=None): """ Return a list of ``ncontours`` colors from the ``colormap`` colorscale. """ if colormap in clrs.PLOTLY_SCALES.keys(): cmap = clrs.PLOTLY_SCALES[colormap] else: raise exceptions.PlotlyError( "Colorscale must be a valid Plotly Colorscale." "The available colorscale names are {}".format( clrs.PLOTLY_SCALES.keys())) values = np.linspace(0, 1, ncontours) vals_cmap = np.array([pair[0] for pair in cmap]) cols = np.array([pair[1] for pair in cmap]) inds = np.searchsorted(vals_cmap, values) if "#" in cols[0]: # for Viridis cols = [clrs.label_rgb(clrs.hex_to_rgb(col)) for col in cols] colors = [cols[0]] for ind, val in zip(inds[1:], values[1:]): val1, val2 = vals_cmap[ind - 1], vals_cmap[ind] interm = (val - val1) / (val2 - val1) col = clrs.find_intermediate_color(cols[ind - 1], cols[ind], interm, colortype="rgb") colors.append(col) return colors
def _any_to_rgb(color: Union[tuple, str]) -> str: c: str = label_rgb(color) if isinstance(color, tuple) else color if c.startswith("#"): c = label_rgb(hex_to_rgb(c)) if not c.startswith("rgb("): raise RuntimeError("Something went wrong with the logic above!") return c
def _colors(ncontours, colormap=None): """ Return a list of ``ncontours`` colors from the ``colormap`` colorscale. """ if colormap in clrs.PLOTLY_SCALES.keys(): cmap = clrs.PLOTLY_SCALES[colormap] else: raise exceptions.PlotlyError( "Colorscale must be a valid Plotly Colorscale." "The available colorscale names are {}".format( clrs.PLOTLY_SCALES.keys())) values = np.linspace(0, 1, ncontours) vals_cmap = np.array([pair[0] for pair in cmap]) cols = np.array([pair[1] for pair in cmap]) inds = np.searchsorted(vals_cmap, values) if '#' in cols[0]: # for Viridis cols = [clrs.label_rgb(clrs.hex_to_rgb(col)) for col in cols] colors = [cols[0]] for ind, val in zip(inds[1:], values[1:]): val1, val2 = vals_cmap[ind - 1], vals_cmap[ind] interm = (val - val1) / (val2 - val1) col = clrs.find_intermediate_color(cols[ind - 1], cols[ind], interm, colortype='rgb') colors.append(col) return colors
def to_rgb_color_list(color_str, default): color_str = color_str.strip() if color_str.startswith("rgb"): return [int(v) for v in color_str.strip("rgba()").split(",")] elif color_str.startswith("#"): return clrs.hex_to_rgb(color_str) else: return default
def graph_options(self, element, ranges, style): opts = super(TriSurfacePlot, self).graph_options(element, ranges, style) copts = self.get_color_opts(element.dimensions()[2], element, ranges, style) opts['colormap'] = [tuple(v/255. for v in colors.hex_to_rgb(c)) for _, c in copts['colorscale']] opts['scale'] = [l for l, _ in copts['colorscale']] opts['show_colorbar'] = self.colorbar return {k: v for k, v in opts.items() if 'legend' not in k and k != 'name'}
def graph_options(self, element, ranges, style): opts = super(TriSurfacePlot, self).graph_options(element, ranges, style) copts = self.get_color_opts(element.dimensions()[2], element, ranges, style) opts['colormap'] = [tuple(v/255. for v in colors.hex_to_rgb(c)) for _, c in copts['colorscale']] opts['scale'] = [l for l, _ in copts['colorscale']] opts['show_colorbar'] = self.colorbar opts['edges_color'] = style.get('edges_color', 'black') opts['plot_edges'] = 'edges_color' in style opts['colorbar'] = copts.get('colorbar', None) return {k: v for k, v in opts.items() if 'legend' not in k and k != 'name'}
) from plotly.express.colors import sequential # noinspection PyProtectedMember from ridgeplot._colors import _path_to_colors_dict # start off by getting all named color-scales defined in PLOTLY_SCALES all_colorscales_raw = PLOTLY_SCALES.copy() # turn plotly's default colors into the default color-scale all_colorscales_raw["default"] = make_colorscale(DEFAULT_PLOTLY_COLORS) # add all sequential color-scales for name, color_list in vars(sequential).items(): if name.startswith("_") or name.startswith("swatches"): continue all_colorscales_raw[name] = make_colorscale(color_list) all_colorscales_clean = {} for name, colorscale in all_colorscales_raw.items(): # convert all color-scales to 'rgb(r, g, b)' format if colorscale[0][1].startswith("#"): colorscale = [[s, label_rgb(hex_to_rgb(c))] for s, c in colorscale] # validate the color-scale as a sanity check and # use lower-case convention for all color-scales validate_colorscale(colorscale) all_colorscales_clean[name.lower()] = colorscale with _path_to_colors_dict.open(mode="w") as _colors_json: json.dump(all_colorscales_clean, _colors_json, indent=2)
def alpha(hex_colour: str, a: float) -> str: """Add an alpha component to a colour represented as a hex string without an alpha component.""" rgb: tuple[int, int, int] = hex_to_rgb(hex_colour) return f"rgba({rgb[0]},{rgb[1]},{rgb[2]},{a})"
def trisurf(x, y, z, simplices, show_colorbar, edges_color, scale, colormap=None, color_func=None, plot_edges=False, x_edge=None, y_edge=None, z_edge=None, facecolor=None): """ Refer to FigureFactory.create_trisurf() for docstring """ # numpy import check if not np: raise ImportError("FigureFactory._trisurf() requires " "numpy imported.") points3D = np.vstack((x, y, z)).T simplices = np.atleast_2d(simplices) # vertices of the surface triangles tri_vertices = points3D[simplices] # Define colors for the triangle faces if color_func is None: # mean values of z-coordinates of triangle vertices mean_dists = tri_vertices[:, :, 2].mean(-1) elif isinstance(color_func, (list, np.ndarray)): # Pre-computed list / array of values to map onto color if len(color_func) != len(simplices): raise ValueError("If color_func is a list/array, it must " "be the same length as simplices.") # convert all colors in color_func to rgb for index in range(len(color_func)): if isinstance(color_func[index], str): if '#' in color_func[index]: foo = colors.hex_to_rgb(color_func[index]) color_func[index] = colors.label_rgb(foo) if isinstance(color_func[index], tuple): foo = colors.convert_to_RGB_255(color_func[index]) color_func[index] = colors.label_rgb(foo) mean_dists = np.asarray(color_func) else: # apply user inputted function to calculate # custom coloring for triangle vertices mean_dists = [] for triangle in tri_vertices: dists = [] for vertex in triangle: dist = color_func(vertex[0], vertex[1], vertex[2]) dists.append(dist) mean_dists.append(np.mean(dists)) mean_dists = np.asarray(mean_dists) # Check if facecolors are already strings and can be skipped if isinstance(mean_dists[0], str): facecolor = mean_dists else: min_mean_dists = np.min(mean_dists) max_mean_dists = np.max(mean_dists) if facecolor is None: facecolor = [] for index in range(len(mean_dists)): color = map_face2color(mean_dists[index], colormap, scale, min_mean_dists, max_mean_dists) facecolor.append(color) # Make sure facecolor is a list so output is consistent across Pythons facecolor = np.asarray(facecolor) ii, jj, kk = simplices.T triangles = graph_objs.Mesh3d(x=x, y=y, z=z, facecolor=facecolor, i=ii, j=jj, k=kk, name='') mean_dists_are_numbers = not isinstance(mean_dists[0], str) if mean_dists_are_numbers and show_colorbar is True: # make a colorscale from the colors colorscale = colors.make_colorscale(colormap, scale) colorscale = colors.convert_colorscale_to_rgb(colorscale) colorbar = graph_objs.Scatter3d( x=x[:1], y=y[:1], z=z[:1], mode='markers', marker=dict( size=0.1, color=[min_mean_dists, max_mean_dists], colorscale=colorscale, showscale=True), hoverinfo='none', showlegend=False ) # the triangle sides are not plotted if plot_edges is False: if mean_dists_are_numbers and show_colorbar is True: return [triangles, colorbar] else: return [triangles] # define the lists x_edge, y_edge and z_edge, of x, y, resp z # coordinates of edge end points for each triangle # None separates data corresponding to two consecutive triangles is_none = [ii is None for ii in [x_edge, y_edge, z_edge]] if any(is_none): if not all(is_none): raise ValueError("If any (x_edge, y_edge, z_edge) is None, " "all must be None") else: x_edge = [] y_edge = [] z_edge = [] # Pull indices we care about, then add a None column to separate tris ixs_triangles = [0, 1, 2, 0] pull_edges = tri_vertices[:, ixs_triangles, :] x_edge_pull = np.hstack([pull_edges[:, :, 0], np.tile(None, [pull_edges.shape[0], 1])]) y_edge_pull = np.hstack([pull_edges[:, :, 1], np.tile(None, [pull_edges.shape[0], 1])]) z_edge_pull = np.hstack([pull_edges[:, :, 2], np.tile(None, [pull_edges.shape[0], 1])]) # Now unravel the edges into a 1-d vector for plotting x_edge = np.hstack([x_edge, x_edge_pull.reshape([1, -1])[0]]) y_edge = np.hstack([y_edge, y_edge_pull.reshape([1, -1])[0]]) z_edge = np.hstack([z_edge, z_edge_pull.reshape([1, -1])[0]]) if not (len(x_edge) == len(y_edge) == len(z_edge)): raise exceptions.PlotlyError("The lengths of x_edge, y_edge and " "z_edge are not the same.") # define the lines for plotting lines = graph_objs.Scatter3d( x=x_edge, y=y_edge, z=z_edge, mode='lines', line=graph_objs.scatter3d.Line( color=edges_color, width=1.5 ), showlegend=False ) if mean_dists_are_numbers and show_colorbar is True: return [triangles, lines, colorbar] else: return [triangles, lines]
def trisurf(x, y, z, simplices, show_colorbar, edges_color, scale, colormap=None, color_func=None, plot_edges=False, x_edge=None, y_edge=None, z_edge=None, facecolor=None): """ Refer to FigureFactory.create_trisurf() for docstring """ # numpy import check if not np: raise ImportError("FigureFactory._trisurf() requires " "numpy imported.") points3D = np.vstack((x, y, z)).T simplices = np.atleast_2d(simplices) # vertices of the surface triangles tri_vertices = points3D[simplices] # Define colors for the triangle faces if color_func is None: # mean values of z-coordinates of triangle vertices mean_dists = tri_vertices[:, :, 2].mean(-1) elif isinstance(color_func, (list, np.ndarray)): # Pre-computed list / array of values to map onto color if len(color_func) != len(simplices): raise ValueError("If color_func is a list/array, it must " "be the same length as simplices.") # convert all colors in color_func to rgb for index in range(len(color_func)): if isinstance(color_func[index], str): if '#' in color_func[index]: foo = colors.hex_to_rgb(color_func[index]) color_func[index] = colors.label_rgb(foo) if isinstance(color_func[index], tuple): foo = colors.convert_to_RGB_255(color_func[index]) color_func[index] = colors.label_rgb(foo) mean_dists = np.asarray(color_func) else: # apply user inputted function to calculate # custom coloring for triangle vertices mean_dists = [] for triangle in tri_vertices: dists = [] for vertex in triangle: dist = color_func(vertex[0], vertex[1], vertex[2]) dists.append(dist) mean_dists.append(np.mean(dists)) mean_dists = np.asarray(mean_dists) # Check if facecolors are already strings and can be skipped if isinstance(mean_dists[0], str): facecolor = mean_dists else: min_mean_dists = np.min(mean_dists) max_mean_dists = np.max(mean_dists) if facecolor is None: facecolor = [] for index in range(len(mean_dists)): color = map_face2color(mean_dists[index], colormap, scale, min_mean_dists, max_mean_dists) facecolor.append(color) # Make sure facecolor is a list so output is consistent across Pythons facecolor = np.asarray(facecolor) ii, jj, kk = simplices.T triangles = graph_objs.Mesh3d(x=x, y=y, z=z, facecolor=facecolor, i=ii, j=jj, k=kk, name='') mean_dists_are_numbers = not isinstance(mean_dists[0], str) if mean_dists_are_numbers and show_colorbar is True: # make a colorscale from the colors colorscale = colors.make_colorscale(colormap, scale) colorscale = colors.convert_colorscale_to_rgb(colorscale) colorbar = graph_objs.Scatter3d( x=x[:1], y=y[:1], z=z[:1], mode='markers', marker=dict(size=0.1, color=[min_mean_dists, max_mean_dists], colorscale=colorscale, showscale=True), hoverinfo='None', showlegend=False) # the triangle sides are not plotted if plot_edges is False: if mean_dists_are_numbers and show_colorbar is True: return graph_objs.Data([triangles, colorbar]) else: return graph_objs.Data([triangles]) # define the lists x_edge, y_edge and z_edge, of x, y, resp z # coordinates of edge end points for each triangle # None separates data corresponding to two consecutive triangles is_none = [ii is None for ii in [x_edge, y_edge, z_edge]] if any(is_none): if not all(is_none): raise ValueError("If any (x_edge, y_edge, z_edge) is None, " "all must be None") else: x_edge = [] y_edge = [] z_edge = [] # Pull indices we care about, then add a None column to separate tris ixs_triangles = [0, 1, 2, 0] pull_edges = tri_vertices[:, ixs_triangles, :] x_edge_pull = np.hstack( [pull_edges[:, :, 0], np.tile(None, [pull_edges.shape[0], 1])]) y_edge_pull = np.hstack( [pull_edges[:, :, 1], np.tile(None, [pull_edges.shape[0], 1])]) z_edge_pull = np.hstack( [pull_edges[:, :, 2], np.tile(None, [pull_edges.shape[0], 1])]) # Now unravel the edges into a 1-d vector for plotting x_edge = np.hstack([x_edge, x_edge_pull.reshape([1, -1])[0]]) y_edge = np.hstack([y_edge, y_edge_pull.reshape([1, -1])[0]]) z_edge = np.hstack([z_edge, z_edge_pull.reshape([1, -1])[0]]) if not (len(x_edge) == len(y_edge) == len(z_edge)): raise exceptions.PlotlyError("The lengths of x_edge, y_edge and " "z_edge are not the same.") # define the lines for plotting lines = graph_objs.Scatter3d(x=x_edge, y=y_edge, z=z_edge, mode='lines', line=graph_objs.Line(color=edges_color, width=1.5), showlegend=False) if mean_dists_are_numbers and show_colorbar is True: return graph_objs.Data([triangles, lines, colorbar]) else: return graph_objs.Data([triangles, lines])