Ray
Ray

Reputation: 8573

Plotly function to convert an RGB colour to RGBA? (Python)

As far as my limited knowledge of Plotly goes, it represents colours as strings like "rgb(23, 57, 211)", or "rgba(23, 57, 211, 0.5)", but I can't find a function that converts from RGB to RGBA. I want this function because I want to add an alpha channel to an RGB colour in DEFAULT_PLOTLY_COLORS" defined in colors.py. I know it's very simple string manipulation and I can write my own function, but is there an official Plotly function to do this?

Upvotes: 3

Views: 3569

Answers (2)

Matthias Luh
Matthias Luh

Reputation: 623

In case anyone also wants to edit the r, g, b values prior to adding the alpha (I can't believe there is no library function doing this, but I didn't find one either):

# imports:
import re
import numpy as np

# constants:
re_pat_color_rgb = re.compile(f"rgb\((\d+),\s?(\d+),\s?(\d+)\)")
re_pat_color_rgba = re.compile(f"rgba\((\d+),\s?(\d+),\s?(\d+),\s?(((\.\d+)|(\d+(\.\d*)?)))\)\)")


# helper functions:
def get_rgb_arr(rgb_string):
    re_match = re_pat_color_rgb.fullmatch(rgb_string)
    if re_match:
        return np.array([int(re_match.group(1)), int(re_match.group(2)), int(re_match.group(3))])  # r, g, b
    return np.array([127, 127, 127])  # error


def get_rgba_arr(rgba_string):
    re_match = re_pat_color_rgba.fullmatch(rgba_string)
    if re_match:
        return np.array([int(re_match.group(1)), int(re_match.group(2)),
                         int(re_match.group(3)), float(re_match.group(4))])  # r, g, b, a
    return np.array([127, 127, 127, 1.0])  # error


def get_rgb_str(rgb_arr):
    return f"rgb(%u,%u,%u)" % (rgb_arr[0], rgb_arr[1], rgb_arr[2])


def get_rgba_str(rgba_arr):
    return f"rgba(%u,%u,%u,%.3f)" % (rgba_arr[0], rgba_arr[1], rgba_arr[2], rgba_arr[3])


# usage:
color_string = "rgb(110,200,70)"  # also works with "rgb(110, 200, 70)"
color_array = get_rgb_arr(color_string)
color_array = 0.7 * color_array + 0.3 * np.array([255, 255, 255])  # mix with 30% white
color_array = np.append(color_array, 200)  # add alpha
my_rgba = get_rgba_str(color_array)  # convert back to string

Upvotes: 0

ConstantinB
ConstantinB

Reputation: 189

As of today, no such function exists to my knowledge. For anyone looking for a solution, this worked just fine for me

def rgb_to_rgba(rgb_value, alpha):
    """
    Adds the alpha channel to an RGB Value and returns it as an RGBA Value
    :param rgb_value: Input RGB Value
    :param alpha: Alpha Value to add  in range [0,1]
    :return: RGBA Value
    """
    return f"rgba{rgb_value[3:-1]}, {alpha})"

Upvotes: 4

Related Questions