当前位置: 首页>>代码示例>>Python>>正文


Python colors.to_hex函数代码示例

本文整理汇总了Python中matplotlib.colors.to_hex函数的典型用法代码示例。如果您正苦于以下问题:Python to_hex函数的具体用法?Python to_hex怎么用?Python to_hex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了to_hex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_dict_from_marker_style

 def get_dict_from_marker_style(line):
     style_dict = {"faceColor": to_hex(line.get_markerfacecolor()),
                   "edgeColor": to_hex(line.get_markeredgecolor()),
                   "edgeWidth": line.get_markeredgewidth(),
                   "markerType": line.get_marker(),
                   "markerSize": line.get_markersize(),
                   "zOrder": line.get_zorder()}
     return style_dict
开发者ID:mantidproject,项目名称:mantid,代码行数:8,代码来源:plotssaver.py

示例2: plot_cdf

    def plot_cdf(self, workload='jankbench', metric='frame_total_duration',
                 threshold=16, tag='.*', kernel='.*', test='.*'):
        """
        Display cumulative distribution functions of a certain metric

        Draws CDFs of metrics in the results. Check ``workloads`` and
        ``workload_available_metrics`` to find the available workloads and
        metrics. Check ``tags``, ``tests`` and ``kernels`` to find the
        names that results can be filtered against.

        The most likely use-case for this is plotting frame rendering times
        under Jankbench, so default parameters are provided to make this easy.

        :param workload: Name of workload to display metrics for
        :param metric: Name of metric to display

        :param threshold: Value to highlight in the plot - the likely use for
                          this is highlighting the maximum acceptable
                          frame-rendering time in order to see at a glance the
                          rough proportion of frames that were rendered in time.

        :param tag: regular expression to filter tags that should be plotted
        :param kernel: regular expression to filter kernels that should be plotted
        :param tag: regular expression to filter tags that should be plotted

        :param by: List of identifiers to group output as in DataFrame.groupby.
        """
        df = self._get_metric_df(workload, metric, tag, kernel, test)
        if df is None:
            return

        test_cnt = len(df.groupby(['test', 'tag', 'kernel']))
        colors = iter(cm.rainbow(np.linspace(0, 1, test_cnt+1)))

        fig, axes = plt.subplots()
        axes.axvspan(0, threshold, facecolor='g', alpha=0.1);

        labels = []
        lines = []
        for keys, df in df.groupby(['test', 'tag', 'kernel']):
            labels.append("{:16s}: {:32s}".format(keys[2], keys[1]))
            color = next(colors)
            cdf = self._get_cdf(df['value'], threshold)
            [units] = df['units'].unique()
            ax = cdf.df.plot(ax=axes, legend=False, xlim=(0,None), figsize=(16, 6),
                             title='Total duration CDF ({:.1f}% within {} [{}] threshold)'\
                             .format(100. * cdf.below, threshold, units),
                             label=test,
                             color=to_hex(color))
            lines.append(ax.lines[-1])
            axes.axhline(y=cdf.below, linewidth=1,
                         linestyle='--', color=to_hex(color))
            self._log.debug("%-32s: %-32s: %.1f", keys[2], keys[1], 100.*cdf.below)

        axes.grid(True)
        axes.legend(lines, labels)
        plt.show()
开发者ID:credp,项目名称:lisa,代码行数:57,代码来源:wa_results_collector.py

示例3: test_cn

def test_cn():
    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['blue', 'r'])
    assert mcolors.to_hex("C0") == '#0000ff'
    assert mcolors.to_hex("C1") == '#ff0000'

    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['xkcd:blue', 'r'])
    assert mcolors.to_hex("C0") == '#0343df'
    assert mcolors.to_hex("C1") == '#ff0000'
开发者ID:AbdealiJK,项目名称:matplotlib,代码行数:10,代码来源:test_colors.py

示例4: test_conversions

def test_conversions():
    # to_rgba_array("none") returns a (0, 4) array.
    assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
    # alpha is properly set.
    assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5))
    # builtin round differs between py2 and py3.
    assert_equal(mcolors.to_hex((.7, .7, .7)), "#b2b2b2")
    # hex roundtrip.
    hex_color = "#1234abcd"
    assert_equal(mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True),
                 hex_color)
开发者ID:717524640,项目名称:matplotlib,代码行数:11,代码来源:test_colors.py

示例5: _get_motif_tree

def _get_motif_tree(tree, data, circle=True, vmin=None, vmax=None):
    try:
        from ete3 import Tree, NodeStyle, TreeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    t = Tree(tree)
    
    # Determine cutoff for color scale
    if not(vmin and vmax):
        for i in range(90, 101):
            minmax = np.percentile(data.values, i)
            if minmax > 0:
                break
    if not vmin:
        vmin = -minmax
    if not vmax:
        vmax = minmax
    
    norm = Normalize(vmin=vmin, vmax=vmax, clip=True)
    mapper = cm.ScalarMappable(norm=norm, cmap="RdBu_r")
    
    m = 25 / data.values.max()
    
    for node in t.traverse("levelorder"):
        val = data[[l.name for l in node.get_leaves()]].values.mean()
        style = NodeStyle()
        style["size"] = 0
        
        style["hz_line_color"] = to_hex(mapper.to_rgba(val))
        style["vt_line_color"] = to_hex(mapper.to_rgba(val))
        
        v = max(np.abs(m * val), 5)
        style["vt_line_width"] = v
        style["hz_line_width"] = v

        node.set_style(style)
    
    ts = TreeStyle()

    ts.layout_fn = _tree_layout
    ts.show_leaf_name= False
    ts.show_scale = False
    ts.branch_vertical_margin = 10

    if circle:
        ts.mode = "c"
        ts.arc_start = 180 # 0 degrees = 3 o'clock
        ts.arc_span = 180
    
    return t, ts
开发者ID:simonvh,项目名称:gimmemotifs,代码行数:52,代码来源:plot.py

示例6: to_rgba_hex

    def to_rgba_hex(c, a):
        """
        Conver rgb color to rgba hex value

        If color c has an alpha channel, then alpha value
        a is ignored
        """
        _has_alpha = has_alpha(c)
        c = mcolors.to_hex(c, keep_alpha=_has_alpha)

        if not _has_alpha:
            arr = colorConverter.to_rgba(c, a)
            return mcolors.to_hex(arr, keep_alpha=True)

        return c
开发者ID:jwhendy,项目名称:plotnine,代码行数:15,代码来源:utils.py

示例7: plotIntersection

 def plotIntersection(self, eq1, eq2, line_type='-',color='Blue'):
     """
     plot the intersection of two linear equations in 3d
     """
     hex_color = colors.to_hex(color)
     bounds = np.array([self.ax.axes.get_xlim(),
                            self.ax.axes.get_ylim(),
                            self.ax.axes.get_zlim()])
     tmp = np.array([np.array(eq1), np.array(eq2)])
     A = tmp[:,:-1]
     b = tmp[:,-1]
     ptlist = []
     for i in range(3):
         vars = [k for k in range(3) if k != i]
         A2 = A[:][:,vars]
         for j in range(2):
             b2 = b - bounds[i,j] * A[:,i]
             try:
                 pt = np.linalg.inv(A2).dot(b2)
             except:
                 continue
             if ((pt[0] >= bounds[vars[0]][0])
                 & (pt[0] <= bounds[vars[0]][1])
                 & (pt[1] >= bounds[vars[1]][0])
                 & (pt[1] <= bounds[vars[1]][1])):
                 point = [0,0,0]
                 point[vars[0]] = pt[0]
                 point[vars[1]] = pt[1]
                 point[i] = bounds[i,j]
                 ptlist.append(point)
     self.plotLine(ptlist, color, line_type)
开发者ID:mcrovella,项目名称:CS132-Geometric-Algorithms,代码行数:31,代码来源:laUtilities.py

示例8: cell_color

 def cell_color(val):
     if val>.9:
         return 'background-color: None'
     else:
         cm =sns.color_palette('Reds', n_colors=100)[::-1]
         color = to_hex(cm[int((val-min_robustness)*50)])
         return 'background-color: %s' % color
开发者ID:IanEisenberg,项目名称:Self_Regulation_Ontology,代码行数:7,代码来源:notebook_utils.py

示例9: swap_colors

def swap_colors(json_file_path):
    '''
    Switches out color ramp in meta.json files.
    Uses custom color ramp if provided and valid; otherwise falls back to nextstrain default colors.
    N.B.: Modifies json in place and writes to original file path.
    '''
    j = json.load(open(json_file_path, 'r'))
    color_options = j['color_options']

    for k,v in color_options.items():
        if 'color_map' in v:
            categories, colors = zip(*v['color_map'])

            ## Use custom colors if provided AND present for all categories in the dataset
            if custom_colors and all([category in custom_colors for category in categories]):
                colors = [ custom_colors[category] for category in categories ]

            ## Expand the color palette if we have too many categories
            elif len(categories) > len(default_colors):
                from matplotlib.colors import LinearSegmentedColormap, to_hex
                from numpy import linspace
                expanded_cmap = LinearSegmentedColormap.from_list('expanded_cmap', default_colors[-1], N=len(categories))
                discrete_colors = [expanded_cmap(i) for i in linspace(0,1,len(categories))]
                colors = [to_hex(c).upper() for c in discrete_colors]

            else: ## Falls back to default nextstrain colors
                colors = default_colors[len(categories)] # based on how many categories are present; keeps original ordering

            j['color_options'][k]['color_map'] = map(list, zip(categories, colors))

    json.dump(j, open(json_file_path, 'w'), indent=1)
开发者ID:blab,项目名称:nextstrain-augur,代码行数:31,代码来源:swap_colors.py

示例10: get_dendrogram_color_fun

def get_dendrogram_color_fun(Z, labels, clusters, color_palette=sns.hls_palette):
    """ return the color function for a dendrogram
    
    ref: https://stackoverflow.com/questions/38153829/custom-cluster-colors-of-scipy-dendrogram-in-python-link-color-func
    Args:
        Z: linkage 
        Labels: list of labels in the order of the dendrogram. They should be
            the index of the original clustered list. I.E. [0,3,1,2] would
            be the labels list - the original list reordered to the order of the leaves
        clusters: cluster assignments for the labels in the original order
    
    """
    dflt_col = "#808080" # Unclustered gray
    color_palette = color_palette(len(np.unique(clusters)))
    D_leaf_colors = {i: to_hex(color_palette[clusters[i]-1]) for i in labels}
    # notes:
    # * rows in Z correspond to "inverted U" links that connect clusters
    # * rows are ordered by increasing distance
    # * if the colors of the connected clusters match, use that color for link
    link_cols = {}
    for i, i12 in enumerate(Z[:,:2].astype(int)):
      c1, c2 = (link_cols[x] if x > len(Z) else D_leaf_colors[x]
        for x in i12)
      link_cols[i+1+len(Z)] = c1 if c1 == c2 else dflt_col
    return lambda x: link_cols[x], color_palette
开发者ID:IanEisenberg,项目名称:Self_Regulation_Ontology,代码行数:25,代码来源:plot_utils.py

示例11: main

def main():
    SIZE = 20
    PLOIDY = 2
    MUTATIONS = 2

    indices = range(SIZE)
    # Build fake data
    seqA = list("0" * SIZE)
    allseqs = [seqA[:] for x in range(PLOIDY)]  # Hexaploid
    for s in allseqs:
        for i in [choice(indices) for x in range(MUTATIONS)]:
            s[i] = "1"

    allseqs = [make_sequence(s, name=name) for (s, name) in \
                zip(allseqs, [str(x) for x in range(PLOIDY)])]

    # Build graph structure
    G = Graph("Assembly graph", filename="graph")
    G.attr(rankdir="LR", fontname="Helvetica", splines="true")
    G.attr(ranksep=".2", nodesep="0.02")
    G.attr('node', shape='point')
    G.attr('edge', dir='none', penwidth='4')

    colorset = get_map('Set2', 'qualitative', 8).mpl_colors
    colorset = [to_hex(x) for x in colorset]
    colors = sample(colorset, PLOIDY)
    for s, color in zip(allseqs, colors):
        sequence_to_graph(G, s, color=color)
    zip_sequences(G, allseqs)

    # Output graph
    G.view()
开发者ID:tanghaibao,项目名称:jcvi,代码行数:32,代码来源:graph.py

示例12: test_color_cycle

def test_color_cycle():
    cyc = plot_utils.color_cycle()
    assert isinstance(cyc, itertools.cycle)
    if mpl_version < '1.5':
        assert next(cyc) == 'b'
    else:
        assert next(cyc) == mpl_colors.to_hex("C0")
开发者ID:gwpy,项目名称:gwpy,代码行数:7,代码来源:test_utils.py

示例13: test_conversions

def test_conversions():
    # to_rgba_array("none") returns a (0, 4) array.
    assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
    # a list of grayscale levels, not a single color.
    assert_array_equal(
        mcolors.to_rgba_array([".2", ".5", ".8"]),
        np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]]))
    # alpha is properly set.
    assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5)
    assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5)
    # builtin round differs between py2 and py3.
    assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2"
    # hex roundtrip.
    hex_color = "#1234abcd"
    assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \
        hex_color
开发者ID:dstansby,项目名称:matplotlib,代码行数:16,代码来源:test_colors.py

示例14: color2hex

def color2hex(color):
    try:
        from matplotlib.colors import to_hex
        result = to_hex(color)
    except ImportError:  # MPL 1.5
        from matplotlib.colors import ColorConverter, rgb2hex
        result = rgb2hex(ColorConverter().to_rgb(color))
    return result
开发者ID:glue-viz,项目名称:glue,代码行数:8,代码来源:matplotlib.py

示例15: test_cn

def test_cn():
    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['blue', 'r'])
    assert mcolors.to_hex("C0") == '#0000ff'
    assert mcolors.to_hex("C1") == '#ff0000'

    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['xkcd:blue', 'r'])
    assert mcolors.to_hex("C0") == '#0343df'
    assert mcolors.to_hex("C1") == '#ff0000'

    matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r'])

    assert mcolors.to_hex("C0") == '#8e4585'
    # if '8e4585' gets parsed as a float before it gets detected as a hex
    # colour it will be interpreted as a very large number.
    # this mustn't happen.
    assert mcolors.to_rgb("C0")[0] != np.inf
开发者ID:shrutishrestha,项目名称:Foreign-Rate-Exchange-Prediction,代码行数:18,代码来源:test_colors.py


注:本文中的matplotlib.colors.to_hex函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。