Matplotlib colours

14 02 2013
Matplotlib supports HTML colour names like ‘AquaMarine’ or ‘BlueViolet’. A complete list of available names can be obtained from this page. But it’s sometimes useful to have a list of all the names inside your program, e.g. if you have plenty (say 10 or 20) different groups of data to be plotted in different colours on a scatter plot. 

import urllib2
from BeautifulSoup import BeautifulSoup

def get_page(url):
    user_agent = 'Mozilla/5 (Solaris 10) Gecko'
    headers = {'User-Agent' : user_agent}
    request = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(request)
    the_page = response.read()
    pool = BeautifulSoup(the_page)
    return pool

pool = get_page('http://www.w3schools.com/html/html_colornames.asp')
res = pool.find('table', attrs={'class' : 'reference'})

# this is the list that will contain the colour names
c = []

for i in range(1, len(res.findAll('tr'))):
    rows = res.findAll('tr')[i]
    cols = rows.findAll('td')
    c.append(str(cols[0].a.string))

# to save in a file
with open('colorlist', 'w+') as f:
    for item in c:
        f.write(item + '\n')
Advertisements