2015-10-27 200 views
1

我希望能夠在matplotlib中使用alpha複製主色('r','g'或'b')的外觀在保持阿爾法爲1的同時,保持alpha爲1.在matplotlib中計算alpha等於0.5的alpha基礎顏色在白色背景下的RGB等效

下面是一個例子,通過手動實驗,我找到了alpha值爲1的RGB值,看起來類似於matplotlib默認顏色alpha 0.5。

我想知道如果有人有一個自動化的方式來實現這一點。

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

+1

這裏差不多quesion:HTTP: //jackvdflow.com/questions/2049230/convert-rgba-color-to-rgb – jakevdp

+0

@jakevdp我不好意思發現;不過,我希望你沒有刪除你的答案; matplotlib用戶會發現你的答案有用,例如你的python函數做映射 – themachinist

回答

3

編輯:您可以使用公式從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

我不知道這是否是標準的,但在我的電腦上了以下工作:

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

基本上,每個組件,你有c + (1 - c) * (1 - a)其中a是你正試圖模擬的alpha值。

對於「簡單」色似(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

def 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))