Reputation: 3950
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)
Upvotes: 17
Views: 36434
Reputation: 16786
To convert a value from that goes from 0 to + infinity to a value that goes from 0.0 to 1.0
import matplotlib.pyplot as plt
price_change = price_change ** 2 / (1 + price_change ** 2)
Blues = plt.get_cmap('Blues')
print Blues(price_change)
A full list of colormaps is here: http://matplotlib.org/users/colormaps.html
Upvotes: 5
Reputation: 2825
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.
Upvotes: 28