How can I group and classify numbers in Python?

I'm not sure if the binning search is correct, but I want to implement the following for a project I'm working on:

I have an array or maybe a dict describing borders and / or areas, for example:

border = OrderedDict ([(10, 'red'), (20, 'blue'), (55, 'purple')])

Areas are indexed from 0 to 100 (for example). I want to classify each area into a color (i.e. less than the key in the dict) and then draw it. For example, if it is less than 10, it is red.

So far I have had:

boundaries = OrderedDict([(10,'red'),(20,'blue'),(55,'purple')])
areas = range(0,101)
binned = []
for area in areas:
    for border in boundaries.keys():
         if area < border:
             binned.append(boundaries[border])
             break

      

Also, I need to figure out a way to define colors and find a package to build it. So if you have any ideas how I can plot a 2D color plot (the actual project will be in 2-D). Maybe matplotlib or PIL? I've used matplotlib before, but never for this data type.

Also, is there a scipy / numpy function that already does what I am trying to do? It would be nice if the code was short and fast. This is not for any purpose (this is for a small experiment / project of mine), so I don't want to reinvent the wheel here.

Thanks in advance for any advice / help.

+3


source to share


1 answer


import matplotlib.pyplot as plt
boundaries = collections.OrderedDict([(10,'red'),(20,'blue'),(55,'purple')])
areas = range(0,101)
n, bins, patches = plt.hist(areas, [0]+list(boundaries), histtype='bar', rwidth=1.0)
for (patch,color) in zip(patches,boundaries.values()):
    patch.set_color(color)
plt.show()

      



+1


source







All Articles