def plotClustering(clustering,
                   dimension=2,
                   colors=['cyan', 'magenta'],
                   centercol='blue',
                   title=None):
    coords = []  # contains one list of coordinate lists for each cluster
    for i in range(len(clustering.keys())):
        coords.append([])  # for each cluster one list
        for j in range(dimension):  # for each dimension one list of coords
            coords[i].append([])
            for point in clustering[list(clustering.keys())[i]]:
                coords[i][j].append(
                    point[j])  # for each point store the respective coordinate
    for sets in coords:
        if len(
                colors
        ) == 0:  # if colors end up empty, generate random new color for next cluster
            cyan = col.to_rgb(col.get_named_colors_mapping()['cyan'])
            magenta = col.to_rgb(col.get_named_colors_mapping()['magenta'])
            c = np.random.rand(3, )
            while (c == cyan).all() or (c == magenta).all():
                c = np.random.rand(3, )
            plt.scatter(sets[0], sets[1], color=c)
        else:
            plt.scatter(sets[0], sets[1], color=colors[0])
            colors = colors[1:]
    # draw the centers:
    for center in clustering.keys():
        plt.scatter(center[0], center[1], color=centercol, marker='x', s=200)
    plt.xlabel('Eruption Time')
    plt.ylabel('Waiting Time')
    plt.title(title)
    plt.show()
Exemple #2
0
def get_color(*args):
    """Convert color name of XKCD color name survey to RGBA tuple.

    Args:
        List of color names. If the list is empty, a full list of
        available color names is returned. Otherwise the first valid
        color in the list is returned as RGBA tuple. If no color is
        valid None is returned.

    """
    try:
        from matplotlib import colors
    except ImportError as err:
        raise ImportError(
            "requires package matplotlib: "
            "https://matplotlib.org") from err

    if not args:
        clist = list(colors.get_named_colors_mapping().keys())
        return sorted([cname[5:].title() \
            for cname in clist if cname[:5] == 'xkcd:'])

    rgb = None
    for cname in args:
        try:
            rgb = colors.to_rgb('xkcd:%s' % cname)
            break
        except ValueError:
            continue
    return rgb
Exemple #3
0
def recolour_image(weight_maps, colours):
    # weight maps are grayscale

    colour_mapping = mc.get_named_colors_mapping()
    colour_vals = np.array(
        [mc.to_rgb(colour_mapping[cname]) for cname in colours])
    bwms = (binarize_weights(wm) for wm in weight_maps)

    # ensuring that the 0 values are translated to white we want to
    # add 1 to each (0,0,0) of the binarized wm so instead of figuring
    # out whatever weird broadcasting method might exist or looping
    # over slowly, just -1 from the colours we are weighting by,
    # multiply in the shifted colours, and then add 1 to the whole image
    coloured_wms = np.array([(c[np.newaxis, np.newaxis, ...] - 1) * wm + 1
                             for c, wm in zip(colour_vals, map(gray2rgb, bwms))
                             ])
    fused = np.ones_like(coloured_wms[0])  # shape: (NxMx3)

    # want the colour of the fused image to be that of largest
    # magnitude of the original weight maps
    brightest = np.max(weight_maps, axis=0)
    for wm, c in zip(weight_maps, colour_vals):
        fused[wm >= brightest] = c

    return coloured_wms, fused
Exemple #4
0
def get_color(*args):
    """Convert color name of XKCD color name survey to RGBA tuple.

    Args:
        List of color names. If the list is empty, a full list of
        available color names is returned. Otherwise the first valid
        color in the list is returned as RGBA tuple. If no color is
        valid None is returned.

    """

    try:
        import matplotlib.colors as colors
    except ImportError:
        raise ImportError("nemoa.common.plot.get_color() requires matplotlib: "
                          "https://matplotlib.org")

    if len(args) == 0:
        clist = list(colors.get_named_colors_mapping().keys())
        return sorted([cname[5:].title() \
            for cname in clist if cname[:5] == 'xkcd:'])

    rgb = None
    for cname in args:
        try:
            rgb = colors.to_rgb('xkcd:%s' % cname)
            break
        except ValueError:
            continue
    return rgb
 def setcolor(self,colorname='white', opacity=0.0):
     colorlist = colors.get_named_colors_mapping().keys()
     if colorname not in colorlist:
         colorname = "xkcd:"+colorname
         if colorname not in colorlist:
             colorname = 'white'
     self.color = np.array(colors.to_rgb(colorname))
     self.opacity = opacity
     True
Exemple #6
0
def sms_ahoy_reply():
    number = request.form['From']
    message_body = request.form['Body']
    print(number)
    print(message_body)
    hex_match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', message_body.lower())
    if message_body.lower() not in colors.get_named_colors_mapping(
    ) and not hex_match:
        if predict([message_body])[0] < 0.7:
            App.set_message(self=tkapp, message=message_body)
        if message_body.lower == '/r':
            App.reset_message()
        message_body = random.choice(
            list(colors.get_named_colors_mapping().values()))
    elif not hex_match:
        message_body = colors.get_named_colors_mapping()[message_body.lower()]

    App.set_colour(self=tkapp, color=message_body)
    App.set_lastnumber(self=tkapp, phone_number=number)
    return None
Exemple #7
0
def list_named_colors(show=None, color_format='rgb255'):
    ''' List all named colors in matplotlib.

    Args:
        show (None | str): the way to list the colors. if show is None,
            this function only return color_dict. Else show is 'print',
            this function print names and colors on screen. Or, this
            function treats show as a file and put names and colors in
            this file.
        color_format (str): the format of color, only can be 'rgb',
            'rgb255', 'hex'.

    Returns:
        if out is None, reture
    '''
    # Build format functions for different color_format.
    assert color_format in ['rgb', 'rgb255', 'hex']
    if color_format == 'rgb':

        def _format_func(color):
            color = mpl_colors.to_rgb(color)
            color_str = f'({color[0]:.3f}, {color[1]:.3f}, {color[2]:.3f})'
            return color, color_str
    elif color_format == 'rgb255':

        def _format_func(color):
            color = mpl_colors.to_rgb(color)
            color = tuple([int(round(255 * c)) for c in color])
            return color, str(color)
    else:

        def _format_func(color):
            color = mpl_colors.to_hex(color)
            return color, color

    # Use _format_func to format colors.
    ori_color_dict = mpl_colors.get_named_colors_mapping()
    color_dict, color_doc = {}, ''
    for name, color in ori_color_dict.items():
        color, color_str = _format_func(color)
        color_dict[name] = color
        color_doc += name + '$' + ' ' * max(25 - len(name),
                                            1) + color_str + '\n'

    # Different ways to show names and colors.
    if show is not None:
        assert isinstance(show, str)
        if show == 'print':
            print(color_doc)
        else:
            assert not osp.exists(show)
            with open(show, 'w') as f:
                f.writelines(color_doc)
    return color_dict
Exemple #8
0
    def getColorFromName(name):
        if name.find("#") == 0:
            return (name)

        colors = mcolors.get_named_colors_mapping()

        color = None

        if name in colors:
            color = colors[name]

        return (color)
Exemple #9
0
 def set_color(self, color):
     if type(color) is list:
         color = tuple(color)
     elif isinstance(color, str):
         print("Converting color string to color")
         aux = colors.get_named_colors_mapping()[color]
         aux = aux.replace('#', '')
         aux = list(map(''.join, zip(*[iter(aux)] * 2)))
         aux = [int(aux[i], 16) for i in range(len(aux))]
         color = tuple(aux)
         color = (int(color[0]), int(color[1]), int(color[2]))
     self.color = color
Exemple #10
0
def make_colours(n, color=None, **kwds):
    if color is None:
        color = get_named_colors_mapping().keys()
    if isinstance(color, collections.Iterable):
        color = list(color)
    if isinstance(color, str) or (isinstance(color, (list, tuple))
                                  and len(color) == 3):
        color = [color]
    if not isinstance(color, np.ndarray):
        color = np.array(color)
    if color.shape[0] < n:
        color = np.tile(color, 1 + n // color.shape[0])
    return color[0:n]
Exemple #11
0
    def test_named(self):
        """Named color parsing..."""
        _config_reset()

        # Try all known Matplotlib colors.
        for color in get_named_colors_mapping().keys():
            _config.read_kwargs(axes_background=color)
            assert _config['pgfutils'].getcolor('axes_background') == color

        # And check it rejects non-existent named colors.
        with pytest.raises(ColorError):
            _config.read_kwargs(axes_background='nonexistentuglycolor')
            _config['pgfutils'].getcolor('axes_background')
Exemple #12
0
    def create_plots(data, read_data, attrs, name, output_dir, project, color=None, legend=None):
        print("Creating " + name + " plots")

        if not isinstance(data, list):
            data = [data]
        if not isinstance(attrs, list):
            attrs = [attrs]

        if color is None:
            color = []
            for index in range(len(data)):
                color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        elif not isinstance(color, list):
            color = [color]

        while len(color) < len(data):
            color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        if legend is None:
            legend = []

        if legend is not None and not isinstance(legend, list):
            legend = [legend]

        while len(legend) < len(data):
            legend.append("Set " + str(len(legend) + 1))


        snpMAF = []
        for (index, data_item) in enumerate(data):
            mm = SNPModule(data=data_item, attributes=attrs[index])
            snpMAF.append({k: v["maf"] for (k, v) in data_item.items()})

        DartGraphs.call_rates_across_snp(data=data, outfile=os.path.join(output_dir, project + "_" + name +"_CallRatesAcrossSNP" + GRAPH_IMG_TYPE), color=color, legend=legend)
        DartGraphs.call_rate_across_individ(data=data, outfile=os.path.join(output_dir, project + "_" + name + "_CallRatesAcrossIndivid" + GRAPH_IMG_TYPE), color=color, legend=legend)
        DartGraphs.maf_across_snp(snp_maf=snpMAF, outfile=os.path.join(output_dir, project + "_" + name + "_MAFAcrossSNP" + GRAPH_IMG_TYPE), color=color, legend=legend)
        DartGraphs.maf_to_read_count(snp_maf=snpMAF, read_data=read_data, outfile=os.path.join(output_dir, project + "_" + name + "_MAFToReadCount" + GRAPH_IMG_TYPE), color=color, legend=legend)
        DartGraphs.call_rate_to_maf(data=data, snp_maf=snpMAF, outfile=os.path.join(output_dir, project + "_" + name + "_CallRateToMAF" + GRAPH_IMG_TYPE), color=color, legend=legend)
Exemple #13
0
def plot2D(X, labels=None):
    assert X.shape[1] == 2
    x = X[:,0]
    y = X[:,1]
    colors = list(mcolors.get_named_colors_mapping().keys())[-19:-9]
    
    if labels is not None:
      for i in range(len(labels)):
        plt.scatter(x[i],y[i],color=colors[int(labels[i])])
        plt.annotate(labels[i], (x[i],y[i]))
    else:
      plt.scatter(x,y)
    plt.show()
Exemple #14
0
def make_module_code():
    elements = [
        header_template.format(timestamp=datetime.utcnow().isoformat(),
                               version=matplotlib.__version__),
        make_enum_code("BaseColor", mcolors.BASE_COLORS),
        make_enum_code("TableauColor", grey_duplicates(mcolors.TABLEAU_COLORS),
                       lambda s: s[4:]),
        make_enum_code("XkcdColor", grey_duplicates(mcolors.XKCD_COLORS),
                       lambda s: s[5:]),
        make_enum_code("Css4Color", mcolors.CSS4_COLORS),
        make_enum_code("Color", mcolors.get_named_colors_mapping()),
    ]
    s = "\n\n\n".join(elements) + "\n"
    return black.format_str(s, mode=black.FileMode({black.TargetVersion.PY36}))
Exemple #15
0
    def aggregate_maps(self, G=[], node_tags={}):
        """
        Takes a list of DiGraphs and aggregates common edges between nodes to create an aggregate graph.
        Attach aggregate graph as an attribute to CoMap object.

        Parameters
        ---------- 
        G : list 
            List of DiGraps
        node_tags : dict 
            Dictionary mapping node numbers to labels, e.g {0:'A',1:'cat',2:'family',...}
        
        Returns
        -------
        None

        """

        self.map = nx.DiGraph()

        # loop over graphs in list of graphs
        for g in G:
            # add nodes to graph
            self.map.add_nodes_from(g.nodes())
            # loop over edges
            for edge in g.edges(data=True):
                # if edge is already present, add weight to edge
                if self.map.has_edge(edge[0], edge[1]):
                    self.map[edge[0]][edge[1]]['weight'] += edge[2]['weight']
                # if edge is not already present, add it with weight=1
                else:
                    self.map.add_edge(edge[0], edge[1], weight=1)

        # relabel nodes according to mapping provided by 'node_tags'
        nx.set_node_attributes(self.map, name='node_label', values=node_tags)
        nx.relabel_nodes(self.map, mapping=node_tags, copy=False)

        # assign a random color to each node
        colour_list = np.random.choice(
            list(colors.get_named_colors_mapping().values()), len(self.map))
        colour_dict = dict(zip(self.map.nodes, colour_list))
        nx.set_node_attributes(self.map, name='node_color', values=colour_dict)

        # save node attributes to CoMap object
        self.node_labels = nx.get_node_attributes(self.map, name='node_label')
        self.node_colors = nx.get_node_attributes(self.map, name='node_color')

        return
Exemple #16
0
    def getColor(self, name):
        if name.find("#") == 0:
            return (name)

        colors = mcolors.get_named_colors_mapping()

        color = None

        if name in colors:
            color = colors[name]
        elif name == "lightest":
            color = self.lightest
        elif name == "darkest":
            color = self.darkest

        return (color)
Exemple #17
0
 def ValueToString(self, value, flag):
     ret_str = ''
     mpl_colors_values_list = list(mpl_utils.MPL_COLORS.values())
     if wx.Colour(value) in mpl_colors_values_list:
         idx = mpl_colors_values_list.index(wx.Colour(value))
         ret_str = list(mpl_utils.MPL_COLORS.keys())[idx]
     #
     mpl_colors_od = OrderedDict(mcolors.get_named_colors_mapping())
     mpl_colors_values_list = list(mpl_colors_od.values())
     #
     if not ret_str:
         value = tuple(c / 255 for c in value)
         if value in mpl_colors_values_list:
             idx = mpl_colors_values_list.index(value)
             ret_str = list(mpl_colors_od.keys())[idx]
     #
     if not ret_str:
         value = mcolors.to_hex(value)
         if value in mpl_colors_values_list:
             idx = mpl_colors_values_list.index(value)
             ret_str = list(mpl_colors_od.keys())[idx]
         else:
             ret_str = value
     #
     if ret_str == 'k':
         ret_str = 'Black'
     elif ret_str == 'w':
         ret_str = 'White'
     elif ret_str == 'b':
         ret_str = 'Blue'
     elif ret_str == 'g':
         ret_str = 'Green'
     elif ret_str == 'r':
         ret_str = 'Red'
     elif ret_str == 'c':
         ret_str = 'Cyan'
     elif ret_str == 'm':
         ret_str = 'Magenta'
     elif ret_str == 'w':
         ret_str = 'Yellow'
     elif ':' in ret_str:
         ret_str = ret_str.split(':')[-1]
     #
     ret_str = ret_str.capitalize()
     #
     return ret_str
Exemple #18
0
    def visualize(self, X, labels=None):
        """ Visualize input 2D embeddings.

    Arguments:
      X: a (N' x d) data matrix (NumPy array)
      labels: a (N' x 1) matrix of numeric labels (NumPy array) - optional
    """
        X = self.reshape_data(X)
        projections = self.project_all(X)
        x = projections[:, 0]
        y = projections[:, 1]
        colors = list(mcolors.get_named_colors_mapping().keys())[-19:-9]

        if labels is not None:
            for i in range(len(labels)):
                plt.scatter(x[i], y[i], color=colors[int(labels[i])])
                plt.annotate(labels[i], (x[i], y[i]))
        else:
            plt.scatter(x, y)
        plt.show()
Exemple #19
0
def colour_by_log_val(graph, branches, logs, get_log_val, \
                      cmap='seismic', \
                      norm=colors.Normalize(vmin=1, vmax=7)):
    grey = colors.get_named_colors_mapping()['tab:gray']
    grey = colors.to_rgba(grey)
    cmap = plt.get_cmap(cmap)
    colours = []
    for commit in graph.nodes:
        try:
            log = logs[commit]
            #should be normalised between 0 and 1
            log_val = get_log_val(log)
            colour = cmap(norm(log_val))
            colours.append(colour)
            #print(log_val, colour)
        except Exception as e:
            #print('log_val not found')
            #print(e)
            colours.append(grey)

    return colours, cmap, norm
def colorname_to_hex(name):
    return colors.get_named_colors_mapping()[name]
Exemple #21
0
    def create_bar_graph(y, title, x_tick_labels, x_label, y_label, outfile, color=None, legend=None):
        # ax = pyplot.axes([0.1, 0.1, 0.8, 0.8])
        fig, ax = pyplot.subplots()
        fig.set_size_inches(15, 9)

        if not isinstance(y, list):
            y = [y]

        if color is None:
            color = []
            for index in range(len(y)):
                color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        elif not isinstance(color, list):
            color = [color]

        while len(color) < len(y):
            color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        if legend is None:
            legend = []

        if legend is not None and not isinstance(legend, list):
            legend = [legend]

        while len(legend) < len(y):
            legend.append("Set " + str(len(legend) + 1))

        if len(y) == 0:
            return

        # x = range(len(y[0]))
        x = numpy.arange(len(y[0]))
        width = .8 / len(y)

        legend_handles = []

        # print(color)

        # Add the graph data
        for (index, val) in enumerate(y):

            ax.bar(x + ((index * width) + (width / 2) - 0.4), val, width, color=color[index])

            if legend is not None:
                patch = patches.Patch(color=color[index], label=legend[index])
                legend_handles.append(patch)

        if len(legend_handles) > 0:
            pyplot.legend(handles=legend_handles)

        # Make the labels look nicer.
        ax.set_title(title, fontdict={'weight': 'bold', 'size': 'large'})
        ax.set_xticklabels(x_tick_labels, fontdict={'style': 'italic'}, rotation=45)
        ax.set_xlabel(x_label, fontdict={'weight': 'bold'})
        ax.set_ylabel(y_label, fontdict={'weight': 'bold'})
        ax.set_xticks(x)

        # Make the x-axis labels light up correctly
        for tick in ax.xaxis.get_majorticklabels():
            tick.set_horizontalalignment("right")

        # Save the graph to file
        pyplot.savefig(outfile, bbox_inches='tight')

        pyplot.close(fig)
Exemple #22
0
    # Test Screen Clear
    SimpleClear()

    # Create 1, 2 and 3 dimensional lists
    a = SimpleDim(5)
    print(a)
    a = SimpleDim(5, 4)
    print(a)
    a = SimpleDim(5, 4, 3)
    print(a)

    print(is_color_like('Saddlebrown'))
    print(is_color_like('#F0123A'))
    print(is_color_like('red'))
    print(is_color_like('marzian'))
    print(get_named_colors_mapping())
    print(is_color_like(None))

    SimpleGrColor('Saddlebrown')

    SimpleBeep()

    # Test Graphics mode
    SimpleGr()

    #help(Canvas)
    #print( canvas.config())
    #exit(0)

    SimpleGrPlot(0, 0)
    SimpleGrPlot(0, 1)
Exemple #23
0
    def create_scatter_plot(x, y, title, x_tick_labels,  x_label, y_label, outfile, color="blue", legend=None, x_ticks=None):
        # ax = pyplot.axes([0.1, 0.1, 0.8, 0.8])
        fig, ax = pyplot.subplots()
        fig.set_size_inches(15, 9)

        width = .5

        if not isinstance(y, list):
            y = [y]
        if not isinstance(x, list):
            x = [x]

        if color is None:
            color = []
            for index in range(len(y)):
                color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        elif not isinstance(color, list):
            color = [color]

        while len(color) < len(y):
            color.append(random.choice(list(colors.get_named_colors_mapping().keys())))

        if legend is None:
            legend = []

        if legend is not None and not isinstance(legend, list):
            legend = [legend]

        while len(legend) < len(y):
            legend.append("Set " + str(len(legend)))

        if len(y) == 0:
            return

        legend_handles = []

        # Add the graph data
        for (index, val) in enumerate(y):
            ax.scatter(x[index], val, width, color=color[index])

            if legend is not None:
                patch = patches.Patch(color=color[index], label=legend[index])
                legend_handles.append(patch)

        if len(legend_handles) > 0:
            pyplot.legend(handles=legend_handles)

        # Make the labels look nicer.
        ax.set_title(title, fontdict={'weight': 'bold', 'size': 'large'})
        ax.set_xlabel(x_label, fontdict={'weight': 'bold'})
        ax.set_ylabel(y_label, fontdict={'weight': 'bold'})

        if x_ticks is not None:
            ax.set_xticks(x_ticks)

        # Set the x axis labels
        if x_tick_labels is not None:
            ax.set_xticklabels(x_tick_labels, fontdict={'style': 'italic'})

        # for tick in ax.xaxis.get_majorticklabels():
        #     tick.set_horizontalalignment("right")

        # Save the graph to file
        pyplot.savefig(outfile, bbox_inches='tight')

        pyplot.close(fig)
Exemple #24
0
from __future__ import division

import rospy
import numpy as np
from matplotlib.colors import get_named_colors_mapping, to_rgb
from geometry_msgs.msg import Point
from visualization_msgs.msg import Marker
from math_utils import rot_unit_vectors

COLOR_MAP = get_named_colors_mapping()

def color_to_rgb_float(color):
    if isinstance(color, str):
        color = to_rgb(COLOR_MAP[color])
    if isinstance(color, tuple) and isinstance(color[0], int):
        color = (color[0]/255, color[1]/255, color[2]/255)
    return color

def colored_marker(color, alpha=1.0):
    color = color_to_rgb_float(color)
    m = Marker()
    m.color.r = color[0]
    m.color.g = color[1]
    m.color.b = color[2]
    m.color.a = alpha
    m.pose.orientation.w = 1.0
    return m

def car_marker(body_frame_id, color = "red", alpha=1.0, CAR_X = 4.22100019455, CAR_Y = 1.76199996471, CAR_dX = 1.3654999733):
    m = colored_marker(color, alpha)
    m.header.frame_id = body_frame_id
Exemple #25
0
def from_hex_color(color_name):
    raw_col = colors.get_named_colors_mapping()["xkcd:" +
                                                color_name].lstrip('#')
    color = tuple(int(raw_col[i:i + 2], 16) for i in (0, 2, 4))
    return color[0] / 256.0, color[1] / 256.0, color[2] / 256.0
Exemple #26
0
            plt.subplot(num_rows+1, n, plot_element+1)
            image = image_data_flat[row[r], :]
            image = image.reshape(28, 28)
            plt.imshow(image)
            plt.axis('off')
            plot_element += 1

        plt.show()





if __name__ == "__main__":

    color_list = mcolors.get_named_colors_mapping()
    mnist = tf.keras.datasets.mnist
    (x_train, y_train), (x_test, y_test) = mnist.load_data()

    data_train = x_train.reshape(len(x_train), -1)
    data_test = x_test.reshape(len(x_test), -1)

    labels_train = y_train
    labels_test = y_test

    clusters = cluster_digit_images(data_test, 10)
    plot_clusters(clusters, data_test, 10)



Exemple #27
0
    from rpi_ws281x import *
except:
    from neopixel_stub import *


try:
    # Python 3
    import http.client as http
except:
    # Python 2
    import httplib as http

import numpy as np
import font454
from matplotlib import colors as mcolors
COLORS = mcolors.get_named_colors_mapping()

from flask import Flask, request, render_template
app = Flask(__name__)


# LED strip configuration:
LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN        = 10      # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10  # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 127  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53

    args = parser.parse_args()

    num_games = args.num_games
    num_moves = args.num_moves

    print("Simulating %d games with %d moves each." % (num_games, num_moves))

    num_fields = 40
    board = np.zeros(num_fields)
    profit_0 = np.zeros(num_fields)
    chance_fields = [FieldPos.CHANCE_1, FieldPos.CHANCE_2, FieldPos.CHANCE_3]
    community_fields = [
        FieldPos.COMMUNITY_1, FieldPos.COMMUNITY_2, FieldPos.COMMUNITY_3
    ]

    color = colors.get_named_colors_mapping()
    # Rents from
    # http://www.math.yorku.ca/~zabrocki/math2042/Monopoly/prices.html
    board_fields = [
        Field("Start", color['springgreen']),
        Field("Mediterranean Avenue", color['sienna'], 2),
        Field("Community Chest", color['gray']),
        Field("Baltic Avenue", color['sienna'], 4),
        Field("Income Tax", color['gray']),
        Station("Reading Railroad", color['black']),
        Field("Oriental Avenue", color['skyblue'], 6),
        Field("Chance", color['gray']),
        Field("Vermont Avenue", color['skyblue'], 6),
        Field("Conneticut Avenue", color['skyblue'], 8),
        Field("Jail", color['springgreen']),
        Field("St. Charles Place", color['violet'], 10),
Exemple #29
0
def get_colors():
    return list(
        filter(not_white,
               mpl_colors.get_named_colors_mapping().values()))
Exemple #30
0
import matplotlib.pyplot as plt
from matplotlib.colors import ColorConverter, ListedColormap, get_named_colors_mapping
import matplotlib.patches as mpatches

DEFAULT_VMIN = 0
DEFAULT_VMAX = 1
DEFAULT_COLORMAP = 'gray'
THRESHOLD = 0.0


def make_colormap(color):
    colors = [np.array(color) / 255 * i for i in range(256)]
    return ListedColormap(colors)


NAMED_COLORS = get_named_colors_mapping()
COLORS = [
    ColorConverter.to_rgb(NAMED_COLORS[color])
    for color in ('tab:blue', 'tab:orange', 'tab:green', 'tab:red',
                  'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray',
                  'tab:olive', 'tab:cyan', 'lime', 'gold', 'indigo', 'w')
]
COLORMAPS = [make_colormap(COLOR) for COLOR in COLORS]


def fuse_canals(im,
                colors=COLORS,
                threshold=THRESHOLD,
                labels=None,
                initial=0,
                legend_anchor=(1, 0.5)):
Exemple #31
0
    "appelgroenvergrijsd": (137, 157, 12),
    "violet": (172, 33, 142),
    "lichtgrijs": (224, 224, 224),  # 12% zwart
    "grijs": (102, 102, 102),  # 60% zwart
    "logogrijs": (115, 115, 115),  # 55% zwart
    "codekleur": (88, 88, 88),
}

# prepend 'cbs:' to all color names to prevent collision
CBS_COLORS = {
    "cbs:" + name: (value[0] / 255, value[1] / 255, value[2] / 255)
    for name, value in CBS_COLORS_RBG.items()
}

# update the matplotlib colors
mcolors.get_named_colors_mapping().update(CBS_COLORS)

# deze dictionairy bevat meerdere palettes
CBS_PALETS = dict(koel=[
    "cbs:corporatelichtblauw",
    "cbs:donkerblauw",
    "cbs:appelgroen",
    "cbs:grasgroen",
    "cbs:oranje",
    "cbs:roze",
],
                  warm=[
                      "cbs:rood",
                      "cbs:geel",
                      "cbs:roze",
                      "cbs:oranje",
Exemple #32
0
 def test_named_color_hex(self):
     """Test if the 'ty:uhh-red' hex-value is correct."""
     assert mcolors.get_named_colors_mapping()['ty:uhh-red'] == '#ee1d23'
Exemple #33
0
 def test_named_color_mapping(self):
     """Test if the typhon colors are available in the name mapping."""
     assert all([
         c in mcolors.get_named_colors_mapping()
         for c in colors.TYPHON_COLORS.keys()
     ])
    def __init__(self,
                 ax,
                 colormap=None,
                 bin_size=5,
                 transpose=False,
                 events=["press", "hover"]):

        self.ax = ax
        if colormap is None:
            colormap = mcolors.get_named_colors_mapping()
        rgb = dict([(n, mcolors.to_rgb(c)) for n, c in colormap.iteritems()])
        hsv = dict([(n, mcolors.rgb_to_hsv(c)) for n, c in rgb.iteritems()])
        colors = [
            n for n, c in rgb.iteritems() if all([v != c[0] for v in c[1:]])
        ]

        groups = {}
        bins = np.arange(0, 360, bin_size) * (1.0 / 360)
        names, hues = zip(*[(n, h) for n, (h, s, v) in hsv.iteritems()])
        for gr, name in zip(np.digitize(hues, bins), names):
            if gr not in groups:
                groups[gr] = []
            groups[gr].append(name)

        self.state = {"selected": None, "background": None}
        self.swatches = []
        self.rgb_to_swatch, self.label_to_swatch = {}, {}

        ordered = lambda c: (c[2], c[1] * -1.0, c[0])
        max_y = 0

        for x, grp in enumerate(
                sorted(groups.itervalues(), key=lambda v: hsv[v[0]][0])):
            for y, name in enumerate(sorted(grp,
                                            key=lambda n: ordered(hsv[n]))):
                if transpose:
                    r = plt.Rectangle((y + 0.1, x + 0.1),
                                      0.8,
                                      0.8,
                                      color=rgb[name])
                else:
                    r = plt.Rectangle((x + 0.1, y + 0.1),
                                      0.8,
                                      0.8,
                                      color=rgb[name])
                ax.add_artist(r)
                sw = Swatch(r, name, self.state)
                sw.connect(events)
                self.swatches.append(sw)
                self.rgb_to_swatch[rgb[name]] = sw
                self.label_to_swatch[name] = sw
                if y > max_y:
                    max_y = y

        if transpose:
            ax.set_xlim(0, max_y + 1), ax.set_ylim(0, len(groups))
        else:
            ax.set_xlim(0, len(groups)), ax.set_ylim(0, max_y + 1)
        ax.set_axis_off()
        ax.figure.subplots_adjust(left=0.02,
                                  right=0.98,
                                  top=0.98,
                                  bottom=0.02,
                                  hspace=0,
                                  wspace=0)
        self.state["background"] = ax.get_figure().canvas.copy_from_bbox(
            ax.bbox)