Python 在matplotlib中从0-1范围获取颜色

Python 在matplotlib中从0-1范围获取颜色,python,matplotlib,Python,Matplotlib,我有很多散点图,我会用图的颜色来表示变量之间的相关性。相关性被标准化为[0,1],我希望蓝色代表0,红色代表1,但我同意其他组合 将我的相关图转换为matplotlib在光谱上显示的东西的代码是什么 for col_s in s_data.columns[1:3]: for col_e in economic_data.columns[1:3]: x= s_data[col_s].interpolate(method='nearest').tolist()

我有很多散点图,我会用图的颜色来表示变量之间的相关性。相关性被标准化为[0,1],我希望蓝色代表0,红色代表1,但我同意其他组合

将我的相关图转换为matplotlib在光谱上显示的东西的代码是什么

for col_s in s_data.columns[1:3]:
    for col_e in economic_data.columns[1:3]:
        x= s_data[col_s].interpolate(method='nearest').tolist()
        y= economic_data[col_e].interpolate(method='nearest').tolist()

        corr=np.corrcoef(x,y)[0,1]
        plt.scatter(x, y, alpha=0.5, c=to_rgb(corr))
        plt.show()

可以指定颜色贴图,然后将颜色定义为依赖于该颜色贴图的相关性。首先,需要从matplotlib导入:

import matplotlib.cm as cm
然后,将代码的打印行更改为:

plt.scatter(x, y, alpha=0.5, c=corr, cmap=cm.rainbow)

您可以使用自定义颜色映射。

您可以将
[0,1]
中的参数映射为十六进制值:

def corr2hex(n):
    ''' Maps a number in [0, 1] to a hex string '''
    if n == 1: return '#fffff'
    else: return '#' + hex(int(n * 16**6))[2:].zfill(6)

print corr2hex(0.31)

>>> 
#4f5c28

然后您可以将其传递给matplotlibs以获取RGB三元组。

谢谢,但我得到了一个错误:“无法将参数类型转换为rgba数组”好的,这是因为x和y为len>1,而corr为单个值。在plot命令中尝试c=str(corr),看看是否有效。不过,这只对灰度有帮助。是的。它运行,但以灰度显示。