Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random colors in matplotlib?

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=??) 

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.

like image 831
John Mee Avatar asked Feb 06 '13 01:02

John Mee


People also ask

How do I generate a random color in python?

Using random() function to generate random colors To begin, import the random function in Python to obtain a random color. The variable r stands for red, g stands for green, and b stands for blue. We already know that the RGB format contains an integer value ranging from 0 to 255.


2 Answers

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

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:

mapping index to color

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.

like image 162
Ali Avatar answered Sep 20 '22 16:09

Ali


for X,Y in data:    scatter(X, Y, c=numpy.random.rand(3,)) 
like image 31
Charles Brunet Avatar answered Sep 19 '22 16:09

Charles Brunet