颜色渐变算法
需求:
给定一组数据,给定渐变颜色两端的颜色值,需要根据这组数据中的每个值大小为其分配一个颜色
算法:
一个需要用颜色表示值大小的数据集weightlist,给定渐变的起始颜色 colorStart={"red":255,"green":50,"blue":47},结束颜色colorend ={"red":139,"green":20,"blue":10},minNum=min(weightlist),maxNum=max(weightlist),weightlist中的一个值number,计算其对应的颜色值color
\[\frac{number-minNum}{maxNum-minNum}=\frac{color-colorStart}{colorend -colorStart}
\]
最终颜色值:
\[color=\frac{(number-minNum)(colorend -colorStart)}{maxNum-minNum}+colorStart
\]
将colorR,colorG,colorB分别代入计算
实现
def getColorstr(value): #将rgb颜色转换为16进制
digit = list(map(str, range(10))) + list("ABCDEF")
if isinstance(value, tuple):
string = '#'
for i in value:
a1 = i // 16
a2 = i % 16
string += digit[a1] + digit[a2]
return string
def gerColorOfWeight1(minNum,maxNum,colorStart,colorend,number): #颜色,根据数值均分
colorR=(colorend["red"]-colorStart["red"])*(number-minNum)/(maxNum-minNum)+colorStart["red"]
colorG=(colorend["green"]-colorStart["green"])*(number-minNum)/(maxNum-minNum)+colorStart["green"]
colorB=(colorend["blue"]-colorStart["blue"])*(number-minNum)/(maxNum-minNum)+colorStart["blue"]
color= "rgb("+str(int(colorR))+','+str(int(colorG))+','+str(int(colorB))+')'
#color=getColorstr((int(colorR),int(colorG),int(colorB)))#转换为16进制颜色
return color
colorYouNeed=gerColorOfWeight1(min(weightlist),max(weightlist),{"red":255,"green":50,"blue":47} ,{"red":139,"green":20,"blue":10} ,1000* errornum/linenum)