简体   繁体   English

如何使用特定的 colors 为矩阵着色?

[英]How can I colour matrix using specific colors?

Here my minimal working example这是我的最小工作示例

arr0 = []
arr1 = []
fig, ax = plt.subplots()

provamatrix =  np.full((750, 750), -1)
arr0 = [random.randint(1,750) for _ in range(100000)]
np.random.shuffle(arr0)
arr1 = [random.randint(1,750) for _ in range(100000)]
np.random.shuffle(arr1)
coordsprova = list(zip(arr0, arr1))
m = 0
for c in coordsprova:
    provamatrix[c] = m
    m += 1
plt.imshow(provamatrix, cmap=plt.cm.Blues)

How can I color the pixels with a -1 value in black?如何用黑色为 -1 值的像素着色?

You can set an "under" color for the colormap.您可以为颜色图设置“下”颜色 A range goes from vmin to vmax.范围从 vmin 到 vmax。 When vmin to vmax aren't set explicitly (and no norm is used) they get calculated from the data.当 vmin 到 vmax 没有明确设置(并且没有使用norm )时,它们是从数据中计算出来的。

Setting vmin to zero, makes all negative values to be 'under'.将 vmin 设置为零,使所有负值都“低于”。 (There is a similar concept of an "over" color for values higher than vmax.) (对于高于 vmax 的值,有一个类似的“过度”颜色概念。)

A colorbar has an option to show the under color in a triangular arrow via plt.colorbar(extend='min') .颜色栏可以通过plt.colorbar plt.colorbar(extend='min')以三角形箭头显示下方颜色。 Other values are 'max', 'both' and 'neither'.其他值是“最大”、“两者”和“都不”。 Related options can show the under color as a rectangle ( extendrect=True ) and set the fraction of the colorbar to be used for the extensions (default 5%: extendfrac=0.05 ).相关选项可以将底色显示为矩形( extendrect=True )并设置用于扩展的颜色条的分数(默认 5%: extendfrac=0.05 )。

Here is some example code to show how it works.下面是一些示例代码来展示它是如何工作的。 Red is used instead of black to illustrate more clearly what's happening.使用红色而不是黑色来更清楚地说明正在发生的事情。 (The code also tries to write the given code a bit more pythonic.) (该代码还尝试将给定的代码编写得更 Pythonic。)

from matplotlib import pyplot as plt
import numpy as np

provamatrix = np.full((750, 750), -1)
coordsprova = np.random.randint(0, 750, (30000, 2))
for m, (i, j) in enumerate(coordsprova):
    provamatrix[i, j] = m
cmap = plt.cm.get_cmap('Blues')
cmap.set_under('red')
plt.imshow(provamatrix, cmap=cmap, vmin=0)
plt.colorbar(extend='min', extendrect=True)
plt.show()

演示图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM