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')
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”).
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.
Percent Opacity = (Black “L” Value/White “L” Value) x 100 (OPAC).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With