在matplotlib中计算白色背景上alpha为0.5的RGB等效基色

时间:2015-10-27 15:23:35

标签: python matplotlib rgb alpha alpha-transparency

我希望能够在matplotlib中使用alpha复制原色(' r','或' b')的外观在白色背景下为0.5,同时将alpha保持为1。

下面是一个示例,通过手动实验,我发现alpha值为1的RGB值与matplotlib默认颜色相似,且alpha值为0.5。

我想知道是否有人有自动实现这一目标的方法。

# export local db to sql file:
mysqldump -uroot -p —-databases qwe_db > qwe_db.sql

# Now you can edit qwe_db.sql file and change db name at top if you want

# import sql file to AWS RDS:
mysql --host=proddb.cfrnxxxxxxx.eu-central-1.rds.amazonaws.com --port=3306 --user=someuser -p qwe_db < qwe_db.sql

enter image description here

2 个答案:

答案 0 :(得分:4)

修改:您可以使用this answer

中的公式

转换为Python,它看起来像这样:

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

所以你可以这样做:

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

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

现在使用此功能,我们可以创建一个确认其有用的图:

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

答案 1 :(得分:1)

我不知道它是否是标准的,但在我的电脑上有以下作品:

newColor = tuple (x + (1 - x) * (1 - a) for x in oldColor)

基本上,对于每个组件,您都有c + (1 - c) * (1 - a),其中a是您要模拟的Alpha值。

对于&#34;简单&#34;颜色如(1, 0, 0)得到(1, 1 - a, 1 - a),黑色(0, 0, 0)得到(1 - a, 1 - a, 1 - a)这是正确的而白色(1, 1, 1)得到(1, 1, 1)也是c正确的。

我尝试了各种alpha和颜色组合,但我仍然没有找到任何不起作用的值,但仍然没有证明这一点;)

以下是我用来随机检查alphadef p (c1, a, f): plt.cla() plt.xlim([4, 6]) plt.ylim([0, 10]) plt.scatter([5], [5], c = c1, edgecolors = 'none', s = 1000, alpha = a, marker = 's') plt.scatter([5], [5.915], c = f(c1, a), edgecolors = 'none', s = 1000, marker = 's') from numpy.random import rand import matplotlib.pyplot as plt p (rand(3), rand(), lambda c, a: c + (1 - c) * (1 - a)) 的不同值的小代码:

n = 4;
A = [1 2 3 4 5 6];

m = numel(A)-n;
B = flipud(convmtx(A,m+1));
B = B(:,m+1:end-m);