gpt4 book ai didi

python - 如何在 matplotlib 中生成随机颜色?

转载 作者:IT老高 更新时间:2023-10-28 21:45:06 30 4
gpt4 key购买 nike

如何生成随机颜色以传递给绘图函数的简单示例是什么?

我在循环中调用 scatter 并希望每个绘图都具有不同的颜色。

for X,Y in data:
scatter(X, Y, c=??)

c: a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however.

最佳答案

I'm calling scatter inside a loop and want each plot in a different color.

基于此,以及您的回答:在我看来,您实际上需要 n distinct 数据集的颜色; 您想将整数索引 0, 1, ..., n-1 映射到不同的 RGB 颜色。 类似:

mapping index to color

这是执行此操作的函数:

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)

在您的代码片段中的用法:

cmap = get_cmap(len(data))
for i, (X, Y) in enumerate(data):
scatter(X, Y, c=cmap(i))

我使用以下代码在我的答案中生成了该图:

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()

使用 Python 2.7 和 matplotlib 1.5 以及 Python 3.5 和 matplotlib 2.0 进行测试。它按预期工作。

关于python - 如何在 matplotlib 中生成随机颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720331/

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