gpt4 book ai didi

具有特定值颜色图的 Python imshow

转载 作者:行者123 更新时间:2023-12-01 07:26:45 27 4
gpt4 key购买 nike

我有一个大小为 2000x200 的二维数组,它可以有 N 个不同的唯一值(大约 20-30 个)。我希望能够使用具有随机颜色(例如 Set3)的 colormap (非线性)来 imshow 这个数组,该颜色映射分配每个唯一值为随机颜色。为此目的使用 Set3 的问题是它为一系列值分配随机颜色,而不是唯一值。该问题的示例如下所示:

enter image description here

最佳答案

您可以创建 n 种颜色(在您的情况下为 20-30),然后为每个值分配随机颜色。请参阅以下代码,了解如何创建 n 种颜色,以及如何为每个矩形分配唯一的颜色。

import matplotlib.pyplot as plt

def get_cmap(n, name='hsv'):
'''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name.'''
return plt.cm.get_cmap(name, n)
def main():
N = 30
fig=plt.figure()
ax=fig.add_subplot(111)
plt.axis('scaled')
ax.set_xlim([ 0, N])
ax.set_ylim([-0.5, 0.5])
cmap = get_cmap(N)
for i in range(N):
rect = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i))
ax.add_artist(rect)
ax.set_yticks([])
plt.show()

if __name__=='__main__':
main()

您可以对每个值执行某种哈希函数,而不是使用 for i in range(N) 。希望对您有帮助。

关于具有特定值颜色图的 Python imshow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406123/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com