Thursday, 3 December 2015

Selecting distinct random colours in Python

I wanted to make a plot of Pfam domains in proteins, and colour them using different colours. The problem is that I needed the domains to have distinct colours, but didn't know in advance how many domains a particular gene family would have. I found a nice Python script by adewes on github for this (thank you!)
[Note: there's a small typo in this script, 'colors.append(generate_new_color(colors),pastel_factor=0.9)' should be 'colors.append(generate_new_color(colors,pastel_factor=0.9))']

An example script to choose 20 distinct random colours and plot them
I made a small example script that chooses 20 distinct random colours, and then makes a plot showing the colours and their hex values. The script on github (mentioned above) gives RGB codes for the colours, and I convert these to hex values for my script. (The script also worked fine when I just plotted the RGB values directly, but I wanted to use the hex values as labels for the colours in the picture produced.)

"""Visualization of random colors.

Simple plot example with the 20 random colors and its visual representation."""# Based on http://matplotlib.org/examples/color/named_colors.html and https://gist.github.com/adewes/5884820