Python matplotlib.colors.to_hex() Examples

The following are 29 code examples of matplotlib.colors.to_hex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.colors , or try the search function .
Example #1
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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 
Example #2
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
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 
Example #3
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #4
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #5
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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 
Example #6
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
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 
Example #7
Source File: plot_utils.py    From arviz with Apache License 2.0 6 votes vote down vote up
def vectorized_to_hex(c_values, keep_alpha=False):
    """Convert a color (including vector of colors) to hex.

    Parameters
    ----------
    c: Matplotlib color

    keep_alpha: boolean
        to select if alpha values should be kept in the final hex values.

    Returns
    -------
    rgba_hex : vector of hex values
    """
    try:
        hex_color = to_hex(c_values, keep_alpha)

    except ValueError:
        hex_color = [to_hex(color, keep_alpha) for color in c_values]
    return hex_color 
Example #8
Source File: plot.py    From osmnx with MIT License 5 votes vote down vote up
def get_colors(n, cmap="viridis", start=0.0, stop=1.0, alpha=1.0, return_hex=False):
    """
    Get n evenly-spaced colors from a matplotlib colormap.

    Parameters
    ----------
    n : int
        number of colors
    cmap : string
        name of a matplotlib colormap
    start : float
        where to start in the colorspace
    stop : float
        where to end in the colorspace
    alpha : float
        opacity, the alpha channel for the RGBa colors
    return_hex : bool
        if True, convert RGBa colors to HTML-like hexadecimal RGB strings. if
        False, return colors as (R, G, B, alpha) tuples.

    Returns
    -------
    color_list : list
    """
    color_list = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, n)]
    if return_hex:
        color_list = [colors.to_hex(c) for c in color_list]
    else:
        color_list = [(r, g, b, alpha) for r, g, b, _ in color_list]
    return color_list 
Example #9
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_color_names():
    assert mcolors.to_hex("blue") == "#0000ff"
    assert mcolors.to_hex("xkcd:blue") == "#0343df"
    assert mcolors.to_hex("tab:blue") == "#1f77b4" 
Example #10
Source File: formlayout.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #11
Source File: formlayout.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #12
Source File: plot_posterior.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def evaluate_cmap(self, cmap, draw_mu, draw_sigma, obs: Union[float, list] = None):
        likelihood_at_observation = stats.norm.pdf(obs, loc=draw_mu, scale=draw_sigma)
        color_fill = colors.to_hex(cmap.to_rgba(np.atleast_1d(likelihood_at_observation)[0]))
        return color_fill 
Example #13
Source File: _formlayout.py    From CogAlg with MIT License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #14
Source File: _formlayout.py    From CogAlg with MIT License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #15
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_color_names():
    assert mcolors.to_hex("blue") == "#0000ff"
    assert mcolors.to_hex("xkcd:blue") == "#0343df"
    assert mcolors.to_hex("tab:blue") == "#1f77b4" 
Example #16
Source File: formlayout.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #17
Source File: formlayout.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #18
Source File: _formlayout.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #19
Source File: canvas.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def mouse_release(self, event):
        if event.button == 1:
            if event.xdata is not None and event.ydata is not None:
                x = int(event.xdata)
                y = int(event.ydata)

                if self.mode > 3 and self.mode <= 6:
                    try:
                        pixel = self.total_mask[x, y, :]
                    except:
                        pixel = [0, 0, 0]
                    pixel_color = matplotlib.colors.to_hex(pixel)
                    color_hex = []
                    patch_color_df = pandas.read_csv('configGUI/patch_color.csv')
                    count = patch_color_df['color'].count()
                    for i in range(count):
                        color_hex.append(matplotlib.colors.to_hex(patch_color_df.iloc[i]['color']))
                    try:
                        ind = color_hex.index(str(pixel_color))
                        self.mask_class = patch_color_df.iloc[ind]['class']
                    except:
                        pass
                    if self.mask_class is not None and self.labelon:
                        self.setToolTip(self.mask_class)

            if not self.labelon:
                self.setToolTip(
                    'Press Enter to choose label\nClick Rectangle or Ellipse to edit\nPress Delete to remove mark')
            else:
                if self.new_shape():
                    self.setToolTip(self.selectedshape_name)

        elif event.button == 2:
            self.wheel_clicked = False

        elif self.picked and event.button == 1:

            self._edit_on_release(event) 
Example #20
Source File: canvas.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def update_selectedShape(self):

        self.selectedShape = self.to_draw

        plist = np.ndarray.tolist(self.selectedShape.get_path().vertices)
        plist = ', '.join(str(x) for x in plist)

        self.df = pandas.read_csv('Markings/marking_records.csv')
        if not self.df[self.df['artist'] == str(self.selectedShape)].index.values.astype(int) == []:
            try:
                self.selectind = self.df[self.df['artist'] == str(self.selectedShape)].index.values.astype(int)[0]
            except:
                self.selectind = 0
        else:
            pass
        color = self.df.iloc[self.selectind]['labelcolor']
        if self.labelon:
            self.setToolTip(self.selectedshape_name)
        if color is np.nan:
            color = colors.to_hex('b', keep_alpha=True)
        self.df.loc[self.selectind, 'path'] = plist

        self.df.to_csv('Markings/marking_records.csv', index=False)
        self.selectedShape.set_facecolor(color)
        self.selectedShape.set_alpha(0.5)

        self.selectionChanged.emit(True)

        try:
            canvas = self.selectedShape.get_figure().canvas
            axes = self.selectedShape.axes
            self.background = canvas.copy_from_bbox(self.selectedShape.axes.bbox)
            canvas.restore_region(self.background)
            axes.draw_artist(self.selectedShape)
            axes.draw_artist(self._corner_handles.artist)
            axes.draw_artist(self._edge_handles.artist)
            axes.draw_artist(self._center_handle.artist)
            # blit just the redrawn area
            canvas.blit(axes.bbox)
        except:
            pass 
Example #21
Source File: labelDialog.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def getColor(self):
        c = self.colorDialog.currentColor()
        color = colors.to_hex(c.name(),keep_alpha=True)
        return color 
Example #22
Source File: swap_colors.py    From augur with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #23
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_color_names():
    assert mcolors.to_hex("blue") == "#0000ff"
    assert mcolors.to_hex("xkcd:blue") == "#0343df"
    assert mcolors.to_hex("tab:blue") == "#1f77b4" 
Example #24
Source File: formlayout.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #25
Source File: formlayout.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #26
Source File: formlayout.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #27
Source File: formlayout.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, color, parent=None):
        QtWidgets.QHBoxLayout.__init__(self)
        assert isinstance(color, QtGui.QColor)
        self.lineedit = QtWidgets.QLineEdit(
            mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent)
        self.lineedit.editingFinished.connect(self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.colorbtn.colorChanged.connect(self.update_text)
        self.addWidget(self.colorbtn) 
Example #28
Source File: _formlayout.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def update_text(self, color):
        self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) 
Example #29
Source File: topography.py    From dynamo-release with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_nullclines(vecfld,
                    lw=3,
                    background=None,
                    save_show_or_return='return',
                    save_kwargs={},
                    ax=None):
    """Plot nullclines stored in the VectorField2D class.

    Arguments
    ---------
        vecfld: :class:`~VectorField2D`
            An instance of the VectorField2D class which presumably has fixed points computed and stored.
        lw: `float` (default: 3)
            The linewidth of the nullcline.
        background: `str` or None (default: None)
            The background color of the plot.
        save_show_or_return: {'show', 'save', 'return'} (default: `return`)
            Whether to save, show or return the figure.
        save_kwargs: `dict` (default: `{}`)
            A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
            will use the {"path": None, "prefix": 'plot_nullclines', "dpi": None, "ext": 'pdf', "transparent": True, "close":
            True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
            according to your needs.
        ax: :class:`~matplotlib.axes.Axes`
            The matplotlib axes used for plotting. Default is to use the current axis.
    """
    from matplotlib import rcParams

    from matplotlib.colors import to_hex

    if background is None:
        _background = rcParams.get("figure.facecolor")
        _background = to_hex(_background) if type(_background) is tuple else _background
    else:
        _background = background

    if _background in ["#ffffff", "black"]:
        colors = ["#189e1a", "#1f77b4"]
    else:
        colors = ["#189e1a", "#1f77b4"]

    if ax is None:
        ax = plt.gca()
    for ncx in vecfld.NCx:
        ax.plot(*ncx.T, c=colors[0], lw=lw)
    for ncy in vecfld.NCy:
        ax.plot(*ncy.T, c=colors[1], lw=lw)

    if save_show_or_return == "save":
        s_kwargs = {"path": None, "prefix": 'plot_nullclines', "dpi": None,
                    "ext": 'pdf', "transparent": True, "close": True, "verbose": True}
        s_kwargs = update_dict(s_kwargs, save_kwargs)

        save_fig(**s_kwargs)
    elif save_show_or_return == "show":
        plt.tight_layout()
        plt.show()
    elif save_show_or_return == "return":
        return ax