首页 > 解决方案 > matplotlib 在 2 种配色方案或 3 种配色方案之间进行选择

问题描述

我有一个从集合 [ -1, 0, 1] 中采样的值图,每个值都映射到一种颜色。但是,可能有一个样本只出现两个不同的值( [-1,0], [-1,1], [0,1] ),如果发生这种情况,那么配色方案应该相应地调整

如果唯一值的数量为 3,则此代码有效

ax2 = plt.subplot2grid((n_rows , 1), (2, 0))
colors = [(216/255, 24/255, 24/255), (1, 1, 1), (143/255, 188/255, 143/255)]    
positions = df['long'].astype(int) - df['short'].astype(int)
cm = LinearSegmentedColormap.from_list('mycols', colors, N=3)
ax2.pcolorfast(ax2.get_xlim(), ax2.get_ylim(),  positions.values[np.newaxis], cmap=cm, alpha=0.5)    

结果是

在此处输入图像描述

我应该如何管理只需要两种颜色的场景?

我认为这控制了段数,但我不知道如何考虑配色方案

cm = LinearSegmentedColormap.from_list('colores', colors, N=len(list(set(positions))))

标签: python-3.xmatplotlib

解决方案


如果您将颜色设置为 numpy 数组,您可以按照以下方式进行操作:colors[np.isin([-1, 0, 1], sorted(available_values))]只选择想要的颜色。当然应该是所有可用值的[-1, 0, 1]完整列表,与colors.

请注意,当值是浮点值时,这可能不起作用,因为比较有时会不准确。

示例代码(未经测试):

all_values = np.array([-1, 0, 1])
colors = np.array([(216/255, 24/255, 24/255), (1, 1, 1), (143/255, 188/255, 143/255)])
positions = df['long'].astype(int) - df['short'].astype(int)
available_values = set(positions)
cm = LinearSegmentedColormap.from_list('mycols', colors[np.isin(all_values, sorted(available_values))], N=len(available_values))
ax2.pcolorfast(ax2.get_xlim(), ax2.get_ylim(),  positions.values[np.newaxis], cmap=cm, alpha=0.5) 

推荐阅读