1

I am trying to generate N random colors P times. For example I have 10 different plots with 20 bars in each and I wan to assign each bar a different color. How can I generate 20 random colors for each bar for 10 times?

I have written this code but it is showing me errors.

def generate_n_random_cmap(how_many=20,list_len=10):
    '''
    Generate list of 20 colors 10 times by default. 
    NOTE: Colors can be duplicated if lit_len is greater than length of plt.colormap()
    '''
    import random
    import matplotlib.pyplot as plt
    c_list = []
    while len(c_list)!=list_len:
        try:
            c_list.append(plt.cm.get_cmap(random.choice(plt.colormaps()),how_many).colors)
        except :
            None
    return random.shuffle(c_list)

And the Error I get is:

'LinearSegmentedColormap' object has no attribute 'colors'

Is there any other method? Colors should be random in nature.

Deshwal
  • 3,436
  • 4
  • 35
  • 94

1 Answers1

2

There are few things. As the error message says, the object you get has no attribute color. As the manual says, Make a linear segmented colormap with name from a sequence of colors which evenly transitions from colors[0] at val=0 to colors[-1] at val=1.

Second, what you do is you're getting a list of paletts. One way of doing what you want is for each graph to randomly select how_many colours you want and then plot your bars accordingly, eg.:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.colors as mcolors

how_many = 20 
# Create a list of colours randomly selected from the list of matplotlib colours
c_list = [np.random.choice(list(mcolors.CSS4_COLORS.values())) for i in range(how_many)] 
barlist=plt.bar(np.arange(len(c_list)), np.arange(len(c_list))) 
for i in range(len(c_list)):
    barlist[i].set_color(c_list[i])

Method one

The other thing you could do is to generate different palettes, eg. using seaborn or even matplotlib, you can use your random selection of a palette np.random.choice(plt.colormaps()). Relevant information can be found in manual of seaborn or those posts: How to give a pandas/matplotlib bar graph custom colors, https://stackoverflow.com/a/18991446/12281892.

My Work
  • 2,143
  • 2
  • 19
  • 47
  • I've found out that there are only certain Colormaps which can produce more than 20 to a million different colors using try catch in a loop. For random, I could have easily used ```random.random()``` in a tuple of 3 followed by a single 1 for ```RGBA``` but that is not what I wanted. Anyways thanks for your help so that I could find the answer. – Deshwal Apr 03 '20 at 04:50