Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate RGB equivalent of base colors with alpha of 0.5 over white background in matplotlib

I would like to be able to replicate the look of a primary color ('r','g' or 'b') in matplotlib with an alpha of 0.5 over a white background, while keeping the alpha at 1.

Here is an example below, where through manual experimentation I've found the RGB values that with an alpha of 1, look similar to matplotlib default colors with an alpha 0.5.

I was wondering if someone had an automated way of achieving this.

import matplotlib.pyplot as plt

s=1000

plt.xlim([4,8])
plt.ylim([0,10])

red=(1,0.55,0.55)
blue=(0.55,0.55,1)
green=(0.54,0.77,0.56)

plt.scatter([5],[5],c='r',edgecolors='none',s=s,alpha=0.5,marker='s')
plt.scatter([6],[5],c='b',edgecolors='none',s=s,alpha=0.5,marker='s')
plt.scatter([7],[5],c='g',edgecolors='none',s=s,alpha=0.5,marker='s')

plt.scatter([5],[5.915],c=red,edgecolors='none',s=s,marker='s')
plt.scatter([6],[5.915],c=blue,edgecolors='none',s=s,marker='s')
plt.scatter([7],[5.915],c=green,edgecolors='none',s=s,marker='s')

enter image description here

like image 550
themachinist Avatar asked Oct 27 '15 15:10

themachinist


People also ask

How do I add transparency to RGB?

Make transparent colors in RThe rgb() command is the key: you define a new color using numerical values (0–255) for red, green and blue. In addition, you set an alpha value (also 0–255), which sets the transparency (0 being fully transparent and 255 being “solid”).

What is alpha value in color?

The alpha component specifies the transparency of the color: 0 is fully transparent, and 255 is fully opaque. Likewise, an A value of 255 represents an opaque color. An A value from 1 through 254 represents a semitransparent color. The color becomes more opaque as A approaches 255.

How is color opacity calculated?

Percent Opacity = (Black “L” Value/White “L” Value) x 100 (OPAC).


1 Answers

Edit: you can use the formula from this answer

Converted to Python, it looks like this:

def make_rgb_transparent(rgb, bg_rgb, alpha):
    return [alpha * c1 + (1 - alpha) * c2
            for (c1, c2) in zip(rgb, bg_rgb)]

So you can do:

red = [1, 0, 0]
white = [1, 1, 1]
alpha = 0.5

make_rgb_transparent(red, white, alpha)
# [1.0, 0.5, 0.5]

Using this function now, we can create a plot that confirms this works:

from matplotlib import colors
import matplotlib.pyplot as plt

alpha = 0.5

kwargs = dict(edgecolors='none', s=3900, marker='s')
for i, color in enumerate(['red', 'blue', 'green']):
    rgb = colors.colorConverter.to_rgb(color)
    rgb_new = make_rgb_transparent(rgb, (1, 1, 1), alpha)
    print(color, rgb, rgb_new)
    plt.scatter([i], [0], color=color, **kwargs)
    plt.scatter([i], [1], color=color, alpha=alpha, **kwargs)
    plt.scatter([i], [2], color=rgb_new, **kwargs)

enter image description here

like image 99
jakevdp Avatar answered Oct 21 '22 08:10

jakevdp