A friend recently tweeted: “Who knows of a python code that intelligently picks colors based on the number needed for a plot?” Phil is plotting several datasets on one plot and wanted an easy way to get a good set of colors to use. I mentioned colorbrewer2.org, which has terrific color maps, but they are locked up in a Flash application. So I had the idea to make a Python package bringing the colorbrewer2.org color maps into Python and connecting them to matplotlib.
There is an existing Python package called colorbrewer but it’s undocumented, doesn’t have its code in a public repository, and is missing some features I wanted. (And it was updated for the first time in 3 years on the day I wrote this post.) It also turns out that the colorbrewer2.org color maps are already in matplotlib (all the capitalized maps in this example) but that doesn’t give access the original colors as defined by colorbrewer2.org. And so was born brewer2mpl.
colorbrewer2.org has three types of color maps: sequential, diverging, and qualitative (for categorical data). Each color map is defined several times with different numbers of colors, anywhere from three to 12.
brewer2mpl packages the colorbrewer2.org color maps and gives access to them as 0-255 RGB triplets, 0-1 RGB triplets, hex strings, and matplotlib color maps. It contains functions for listing color maps by type and number of defined colors. Now Phil can do the following to get some good colors to use in matplotlib plots:
import brewer2mpl bmap = brewer2mpl.get_map('Set1', 'qualitative', 5) colors = bmap.mpl_colors
For more information:
- PyPI: http://pypi.python.org/pypi/brewer2mpl
- GitHub: https://github.com/jiffyclub/brewer2mpl
- Wiki: https://github.com/jiffyclub/brewer2mpl/wiki
This was my first time building and releasing my own package. It was fun and a great chance to learn about the simplest aspects of releasing Python packages. (Nothing fancy going on here.) Hope I get the chance to do more!
Hi Matt,
thank you very much for this nice package! I am already using it on a daily basis.
When I tried to install it on a machine running python 2.6 I got an error message “ValueError: zero length field name in format”. I could fix this by replacing {:>02} with {0:>02} in line 151 in brewer2mpl.py. Hope this helps!
Cheers!
otto
Thanks for the report, I’ll fix that!
[…] wrote brewer2mpl a couple years ago to help people use colorbrewer2 color palettes in Python. Since then it’s expanded to include […]