本文介绍了如何在 matplotlib 中生成随机颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

数据中X,Y的

 :分散(X,Y,c=??)

c:一种颜色.c可以是单个颜色格式字符串,也可以是长度为N的颜色规范序列,也可以是使用通过kwargs指定的cmap和norm映射到颜色的N个数字序列(请参见下文).请注意,c不应为单个数字RGB或RGBA序列,因为这与要进行颜色映射的值数组是无法区分的.然而,c 可以是一个二维数组,其中的行是 RGB 或 RGBA.

解决方案

基于此,并根据您的回答:在我看来,您实际上希望为数据集提供 n distinct 颜色;您想将整数索引 0、1,...,n-1 映射到不同的RGB颜色.类似于:

这是执行此操作的函数:

 将matplotlib.pyplot导入为pltdef get_cmap(n, name='hsv'):'''返回一个将0、1,...,n-1中的每个索引映射到一个不同的函数RGB颜色;关键字参数名称必须是标准的 mpl 颜色图名称.'''返回plt.cm.get_cmap(name,n)

在问题中的代码片段中的用法:

  cmap = get_cmap(len(data))对于i,(X,Y)枚举(数据):分散(X,Y,c=cmap(i))

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

 将matplotlib.pyplot导入为pltdef get_cmap(n,name ='hsv'):'''返回一个将0、1,...,n-1中的每个索引映射到一个不同的函数RGB颜色;关键字参数名称必须是标准的 mpl 颜色图名称.'''返回 plt.cm.get_cmap(name, n)定义主():N = 30fig=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)对于范围(N)中的i:rect = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i))ax.add_artist(rect)ax.set_yticks([])plt.show()如果__name __ =='__ main__':主要的()

使用 Python 2.7 和matplotlib 1.5 和 Python 3.5 &matplotlib 2.0.它按预期工作.

What's the trivial example of how to generate random colors for passing to plotting functions?

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

for X,Y in data:
   scatter(X, Y, c=??)
解决方案

Based on that, and on your answer: It seems to me that you actually want n distinct colors for your datasets; you want to map the integer indices 0, 1, ..., n-1 to distinct RGB colors. Something like:

Here is the function to do it:

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)

Usage in your pseudo-code snippet in the question:

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


I generated the figure in my answer with the following code:

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

Tested with both Python 2.7 & matplotlib 1.5, and with Python 3.5 & matplotlib 2.0. It works as expected.

这篇关于如何在 matplotlib 中生成随机颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 18:22
查看更多