Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data values into color information for matplotlib?

I am using the class matplotlib.patches.Polygon to draw polygons on a map. In fact, the information about the coordinates of the corners of the polygons and a floating point data value for each "polygon" are given. Now I'd like to convert these data values (ranging from 0 to 3e15) into color information to visualize it nicely. What is the best practice for doing that in Python?

A snippet of my code:

poly = Polygon( xy, facecolor=data, edgecolor='none')
plt.gca().add_patch(poly)
like image 492
HyperCube Avatar asked Oct 12 '12 11:10

HyperCube


1 Answers

In the RGB color system two bits of data are used for each color, red, green, and blue. That means that each color runs on a scale from 0 to 255. Black would be 00,00,00, while white would be 255,255,255. Matplotlib has lots of pre-defined colormaps for you to use. They are all normalized to 255, so they run from 0 to 1. So you need only normalize your data, then you can manually select colors from a color map as follows:

>>> import matplotlib.pyplot as plt

>>> Blues = plt.get_cmap('Blues')
>>> print Blues(0)
(0.9686274528503418, 0.9843137264251709, 1.0, 1.0)
>>> print Blues(0.5)
(0.41708574119736169, 0.68063054575639614, 0.83823145908467911, 1.0)
>>> print Blues(1.0)
(0.96555171293370867, 0.9823452528785257, 0.9990157632266774, 1.0)

Here are all of the predefined colormaps. If you're interested in creating your own color maps, here is a good example. Also here is a paper from IBM on choosing colors carefully, something you should be considering if you're using color to visualize data.

like image 65
Mr. Squig Avatar answered Sep 17 '22 09:09

Mr. Squig