python-3.x - 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))))
解决方案
如果您将颜色设置为 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)
推荐阅读
- java - 如何从Java中的参数调用不同的方法?
- sql-server - 从 SQL Server 向 ADFS 添加自定义声明
- sql - 将 varchar 转换为 int(奇怪的情况?)
- python - 没有按位交集的 Numpy 广播按位联合
- android - 根据图像视图的大小滑动加载质量照片[如果尺寸小(图标)则低]
- sql-server - 如何在 SQL 中从用户定义的日期添加 1 天?
- angular - Angular - 从组件更新服务的属性
- oracle - 在oracle中触发以防止插入重复数据
- java - 有人可以向我解释一下使用移位将两个变量相乘的代码吗?
- sql-server - AWS Lambda、Python 和 SQL Server