Ejemplo n.º 1
0
def get_colorscale(name):
    """
    Returns the colorscale for a given name. See `named_colorscales` for the
    built-in colorscales.
    """
    from _plotly_utils.basevalidators import ColorscaleValidator

    if not isinstance(name, str):
        raise exceptions.PlotlyError("Name argument have to be a string.")

    name = name.lower()
    if name[-2:] == "_r":
        should_reverse = True
        name = name[:-2]
    else:
        should_reverse = False

    if name in ColorscaleValidator("", "").named_colorscales:
        colorscale = ColorscaleValidator("", "").named_colorscales[name]
    else:
        raise exceptions.PlotlyError(
            f"Colorscale {name} is not a built-in scale.")

    if should_reverse:
        colorscale = colorscale[::-1]
    return make_colorscale(colorscale)
Ejemplo n.º 2
0
def make_colorscale(colors, scale=None):
    """
    Makes a colorscale from a list of colors and a scale

    Takes a list of colors and scales and constructs a colorscale based
    on the colors in sequential order. If 'scale' is left empty, a linear-
    interpolated colorscale will be generated. If 'scale' is a specificed
    list, it must be the same legnth as colors and must contain all floats
    For documentation regarding to the form of the output, see
    https://plot.ly/python/reference/#mesh3d-colorscale

    :param (list) colors: a list of single colors
    """
    colorscale = []

    # validate minimum colors length of 2
    if len(colors) < 2:
        raise exceptions.PlotlyError(
            "You must input a list of colors that has at least two colors.")

    if scale is None:
        scale_incr = 1.0 / (len(colors) - 1)
        return [[i * scale_incr, color] for i, color in enumerate(colors)]

    else:
        if len(colors) != len(scale):
            raise exceptions.PlotlyError(
                "The length of colors and scale must be the same.")

        validate_scale_values(scale)

        colorscale = [list(tup) for tup in zip(scale, colors)]
        return colorscale
Ejemplo n.º 3
0
def validate_scale_values(scale):
    """
    Validates scale values from a colorscale

    :param (list) scale: a strictly increasing list of floats that begins
        with 0 and ends with 1. Its usage derives from a colorscale which is
        a list of two-lists (a list with two elements) of the form
        [value, color] which are used to determine how interpolation weighting
        works between the colors in the colorscale. Therefore scale is just
        the extraction of these values from the two-lists in order
    """
    if len(scale) < 2:
        raise exceptions.PlotlyError(
            "You must input a list of scale values that has at least two values."
        )

    if (scale[0] != 0) or (scale[-1] != 1):
        raise exceptions.PlotlyError(
            "The first and last number in your scale must be 0.0 and 1.0 "
            "respectively.")

    if not all(x < y for x, y in zip(scale, scale[1:])):
        raise exceptions.PlotlyError(
            "'scale' must be a list that contains a strictly increasing "
            "sequence of numbers.")
Ejemplo n.º 4
0
def validate_colors_dict(colors, colortype="tuple"):
    """
    Validates dictionary of color(s)
    """
    # validate each color element in the dictionary
    for key in colors:
        if "rgb" in colors[key]:
            colors[key] = color_parser(colors[key], unlabel_rgb)
            for value in colors[key]:
                if value > 255.0:
                    raise exceptions.PlotlyError(
                        "Whoops! The elements in your rgb colors "
                        "tuples cannot exceed 255.0.")
            colors[key] = color_parser(colors[key], unconvert_from_RGB_255)

        if "#" in colors[key]:
            colors[key] = color_parser(colors[key], hex_to_rgb)
            colors[key] = color_parser(colors[key], unconvert_from_RGB_255)

        if isinstance(colors[key], tuple):
            for value in colors[key]:
                if value > 1.0:
                    raise exceptions.PlotlyError(
                        "Whoops! The elements in your colors tuples "
                        "cannot exceed 1.0.")

    if colortype == "rgb":
        for key in colors:
            colors[key] = color_parser(colors[key], convert_to_RGB_255)
            colors[key] = color_parser(colors[key], label_rgb)

    return colors
Ejemplo n.º 5
0
def validate_colorscale(colorscale):
    """Validate the structure, scale values and colors of colorscale."""
    if not isinstance(colorscale, list):
        # TODO Write tests for these exceptions
        raise exceptions.PlotlyError("A valid colorscale must be a list.")
    if not all(isinstance(innerlist, list) for innerlist in colorscale):
        raise exceptions.PlotlyError(
            "A valid colorscale must be a list of lists.")
    colorscale_colors = colorscale_to_colors(colorscale)
    scale_values = colorscale_to_scale(colorscale)

    validate_scale_values(scale_values)
    validate_colors(colorscale_colors)
Ejemplo n.º 6
0
def convert_dict_colors_to_same_type(colors_dict, colortype="rgb"):
    """
    Converts a colors in a dictioanry of colors to the specified color type

    :param (dict) colors_dict: a dictioanry whose values are single colors
    """
    for key in colors_dict:
        if "#" in colors_dict[key]:
            colors_dict[key] = color_parser(colors_dict[key], hex_to_rgb)
            colors_dict[key] = color_parser(colors_dict[key], label_rgb)

        elif isinstance(colors_dict[key], tuple):
            colors_dict[key] = color_parser(colors_dict[key],
                                            convert_to_RGB_255)
            colors_dict[key] = color_parser(colors_dict[key], label_rgb)

    if colortype == "rgb":
        return colors_dict
    elif colortype == "tuple":
        for key in colors_dict:
            colors_dict[key] = color_parser(colors_dict[key], unlabel_rgb)
            colors_dict[key] = color_parser(colors_dict[key],
                                            unconvert_from_RGB_255)
        return colors_dict
    else:
        raise exceptions.PlotlyError("You must select either rgb or tuple "
                                     "for your colortype variable.")
Ejemplo n.º 7
0
def convert_colors_to_same_type(
    colors,
    colortype="rgb",
    scale=None,
    return_default_colors=False,
    num_of_defualt_colors=2,
):
    """
    Converts color(s) to the specified color type

    Takes a single color or an iterable of colors, as well as a list of scale
    values, and outputs a 2-pair of the list of color(s) converted all to an
    rgb or tuple color type, aswell as the scale as the second element. If
    colors is a Plotly Scale name, then 'scale' will be forced to the scale
    from the respective colorscale and the colors in that colorscale will also
    be coverted to the selected colortype. If colors is None, then there is an
    option to return portion of the DEFAULT_PLOTLY_COLORS

    :param (str|tuple|list) colors: either a plotly scale name, an rgb or hex
        color, a color tuple or a list/tuple of colors
    :param (list) scale: see docs for validate_scale_values()

    :rtype (tuple) (colors_list, scale) if scale is None in the function call,
        then scale will remain None in the returned tuple
    """
    colors_list = []

    if colors is None and return_default_colors is True:
        colors_list = DEFAULT_PLOTLY_COLORS[0:num_of_defualt_colors]

    if isinstance(colors, str):
        if colors in PLOTLY_SCALES:
            colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
            if scale is None:
                scale = colorscale_to_scale(PLOTLY_SCALES[colors])

        elif "rgb" in colors or "#" in colors:
            colors_list = [colors]

    elif isinstance(colors, tuple):
        if isinstance(colors[0], Number):
            colors_list = [colors]
        else:
            colors_list = list(colors)

    elif isinstance(colors, list):
        colors_list = colors

    # validate scale
    if scale is not None:
        validate_scale_values(scale)

        if len(colors_list) != len(scale):
            raise exceptions.PlotlyError(
                "Make sure that the length of your scale matches the length "
                "of your list of colors which is {}.".format(len(colors_list)))

    # convert all colors to rgb
    for j, each_color in enumerate(colors_list):
        if "#" in each_color:
            each_color = color_parser(each_color, hex_to_rgb)
            each_color = color_parser(each_color, label_rgb)
            colors_list[j] = each_color

        elif isinstance(each_color, tuple):
            each_color = color_parser(each_color, convert_to_RGB_255)
            each_color = color_parser(each_color, label_rgb)
            colors_list[j] = each_color

    if colortype == "rgb":
        return (colors_list, scale)
    elif colortype == "tuple":
        for j, each_color in enumerate(colors_list):
            each_color = color_parser(each_color, unlabel_rgb)
            each_color = color_parser(each_color, unconvert_from_RGB_255)
            colors_list[j] = each_color
        return (colors_list, scale)
    else:
        raise exceptions.PlotlyError("You must select either rgb or tuple "
                                     "for your colortype variable.")
Ejemplo n.º 8
0
def validate_colors(colors, colortype="tuple"):
    """
    Validates color(s) and returns a list of color(s) of a specified type
    """
    from numbers import Number

    if colors is None:
        colors = DEFAULT_PLOTLY_COLORS

    if isinstance(colors, str):
        if colors in PLOTLY_SCALES:
            colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
            # TODO: fix _gantt.py/_scatter.py so that they can accept the
            # actual colorscale and not just a list of the first and last
            # color in the plotly colorscale. In resolving this issue we
            # will be removing the immediate line below
            colors = [colors_list[0]] + [colors_list[-1]]
        elif "rgb" in colors or "#" in colors:
            colors = [colors]
        else:
            raise exceptions.PlotlyError(
                "If your colors variable is a string, it must be a "
                "Plotly scale, an rgb color or a hex color.")

    elif isinstance(colors, tuple):
        if isinstance(colors[0], Number):
            colors = [colors]
        else:
            colors = list(colors)

    # convert color elements in list to tuple color
    for j, each_color in enumerate(colors):
        if "rgb" in each_color:
            each_color = color_parser(each_color, unlabel_rgb)
            for value in each_color:
                if value > 255.0:
                    raise exceptions.PlotlyError(
                        "Whoops! The elements in your rgb colors "
                        "tuples cannot exceed 255.0.")
            each_color = color_parser(each_color, unconvert_from_RGB_255)
            colors[j] = each_color

        if "#" in each_color:
            each_color = color_parser(each_color, hex_to_rgb)
            each_color = color_parser(each_color, unconvert_from_RGB_255)

            colors[j] = each_color

        if isinstance(each_color, tuple):
            for value in each_color:
                if value > 1.0:
                    raise exceptions.PlotlyError(
                        "Whoops! The elements in your colors tuples "
                        "cannot exceed 1.0.")
            colors[j] = each_color

    if colortype == "rgb" and not isinstance(colors, six.string_types):
        for j, each_color in enumerate(colors):
            rgb_color = color_parser(each_color, convert_to_RGB_255)
            colors[j] = color_parser(rgb_color, label_rgb)

    return colors