Friday 27 November 2015

Making a key for colours in Python using matplotlib

I have different colours assigned to categories in a big plot, but don't have room in that plot to show a key for the colours. So I decided to make a separate key for the colours using matplotlib in Python.

I found a nice example of plotting colours in matplotlib called named_colors.py, and used that as my starting point.

My input: a list of colours, and labels for them
Then I edited the code a bit. I had a list of colours I'm interested in, and a list of labels for them:
hex_ =  [ u'#FFFF00', u'#006400',      u'#00ff7f',    u'#7cfc00',       u'#00F5FF', u'#0000ff',  u'#FFA500',     u'#8B8682',      u'#A78D84',           u'#A52A2A',         u'#ff1493',                     u'#ff69b4',         u'#FF0000' , u'#660000', u'#000000' ]
names = [ 'I' ,     'III-Ascaridida','III-Oxyurida','III-Spirurida',      'IVa',    'IVb',      'V-AS',      'V-Free-Living', 'V-Strongylid-Lungworm', 'V-Strongylid-Other', 'Trematodes-Schistosomatids', 'Trematodes-Other', 'Cestodes', 'Flatworms-Other', 'Outgroup']


My code
Here's the code I found to work:
"""
Visualization of named colors.

Simple plot example with the named colors and its visual representation.
"""
# Based on http://matplotlib.org/examples/color/named_colors.html

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import numpy as np
import matplotlib.pyplot as plt


# Take my colors of interest:
hex_ =  [ u'#FFFF00', u'#006400',      u'#00ff7f',    u'#7cfc00',       u'#00F5FF', u'#0000ff',  u'#FFA500',     u'#8B8682',      u'#A78D84',           u'#A52A2A',         u'#ff1493',                     u'#ff69b4',         u'#FF0000' , u'#660000', u'#000000' ]
names = [ 'I' ,     'III-Ascaridida','III-Oxyurida','III-Spirurida',      'IVa',    'IVb',      'V-AS',      'V-Free-Living', 'V-Strongylid-Lungworm', 'V-Strongylid-Other', 'Trematodes-Schistosomatids', 'Trematodes-Other', 'Cestodes', 'Flatworms-Other', 'Outgroup']

n = len(hex_)
ncols = 4
nrows = int(np.ceil(1. * n / ncols))

fig, ax = plt.subplots()

X, Y = fig.get_dpi() * fig.get_size_inches()

# row height
h = Y / (nrows + 1)
# col width
w = X / ncols

for (i, color) in enumerate(hex_):
    name = names[i]
    col = i % ncols
    row = int(i / ncols)
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.075),
            horizontalalignment='left',
            verticalalignment='center')

    # Add extra black line a little bit thicker to make
    # clear colors more visible.
    ax.hlines(y, xi_line, xf_line, color='black', linewidth=(h * 0.7))
    ax.hlines(y + h * 0.1, xi_line, xf_line, color=color, linewidth=(h * 0.6))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.savefig("colour_key.png")


Output of my code:
This makes this key for my colours:

















Other Notes:
- Something useful I found is a list of all the named colours in matplotlib, and their hex values: here
- Our collaborator Bruce Rosa pointed out the nice website http://paletton.com for choosing colour schemes for figures. Another nice one is colorbrewer

No comments: